无法将输出重定向到文件

Cant redirect output to a file

tail -f /var/log/kern.log | sed 's/.* //'

在终端上给我输出,但是当我这样做时

 tail -f /var/log/kern.log | sed 's/.* //' >> logfile.txt

我在文件中找不到任何内容。我从内核模块打印可执行文件的名称。例如,如果我 运行 lskern.log/bin/ls 但有时间戳等。所以我尝试上面的方法只提取路径并且只要我 运行 它没有重定向到输出文件,我也试过 tee logfile.txt 。依然没有。请帮忙。

对不起,不是只有一个“>”可以把一个内容放入文件吗?

您的 sed 命令的问题是您使用 "everything that is followed by a space"(“.*”)并将其替换为 "nothing"。你需要做的是抓取第一个 space 之前的所有内容并保存,然后用保存的位替换所有内容。要保存部分输入字符串,请将正则表达式的那部分放在括号中:(.*) 然后可以使用 </code> 将其放入替换字符串中。 </p> <p>但不仅如此。 sed 是贪婪的——它会尽可能多地获取。所以当你有一个像 "abc def ghi" 这样的字符串时,它会看到 "abc def" 后面跟着一个 space 并抓住所有这些。所以问题是,如何只得到第一部分,直到第一个 space?</p> <p>您可以 select 后跟 space 的所有非分隔符(space)的字符。所以在上面的例子中,因为 <strong>c</strong> 和 <strong>d</strong> 之间的字符是 space,所以不会是 selected,只有 <strong>abc</strong> 部分会。 </p> <p>所以你最终得到的是:</p> <pre><code>sed "s/\([^ ]*\) .*//"`

其中匹配模式包括 "anything that's not a space, as many as there are"(在括号中以保存它)"([^ ]\*)"、单个 space " ",然后是任何其他内容 ".*"。替换字符串 "" 是 "whatever matched the part of the regex in the first set of parentheses"。

这是我做的一个快速测试:

Testing: cat testout.txt
cat: testout.txt: No such file or directory

Testing: cat testin.txt
abc def ghi
asdf jkl; fdsa ;lkj qwerty 123
Once upon a time
When in the course

Testing: cat testin.txt | sed "s/\([^ ]*\) .*//" >> testout.txt

Testing: cat testout.txt
abc
asdf
Once
When

Testing: cat testin.txt | sed "s/\([^ ]*\) .*//" >> testout.txt

Testing: cat testout.txt
abc
asdf
Once
When
abc
asdf
Once
When

Testing:

它从 testout.txt 中的任何内容和 testin.txt 中的 4 行开始。然后它将 testin.txt 的内容发送到 sed 并将输出附加到文件。然后显示内容。然后,我又做了一次,以表明它确实在追加(现在 testout.txt 中有 8 行,两组 4。)(注意:我只是添加了空行使其更易于阅读。)

如果您有任何问题,请告诉我。

希望对您有所帮助!