在 cat 命令中向文件追加一行?

Dou*_*ass 13 command-line pipe cat echo

我可以cat file.txt获取文件的内容,但我也想添加我自己选择的最后一行。

我试过管道,(cat file.txt ; echo "My final line") |但只有最后一条线穿过管道。我怎样才能加入猫和最后一行?

编辑澄清一点:我不想修改文件本身。我知道,如果是这种情况,我可以做echo "My final line" >> file.txtecho "My final line" | tee -a file.txt但我只是尝试在此特定命令的上下文中执行附加操作,因此我可以通过管道连接file.txtand "My final line"

小智 34

您可以利用cat从 stdin 读取的能力以及读取多个文件的能力来实现这一点。

~$ cat file.txt
Hello from file.txt

~$ echo "My final line" | cat file.txt -
Hello from file.txt
My final line
Run Code Online (Sandbox Code Playgroud)

您还可以预先添加一行,例如:

~$ echo "My final line" | cat - file.txt
My final line
Hello from file.txt
Run Code Online (Sandbox Code Playgroud)

请注意,您不仅限于一行。cat将从标准输入读取直到到达 EOF。curl例如,您可以将 的输出传递到 的输出前或附加到 的输出cat

~$ curl -s http://perdu.com | cat file.txt -
Hello from file.txt
<html><head><title>Vous Etes Perdu ?</title></head><body><h1>Perdu sur l'Internet ?</h1><h2>Pas de panique, on va vous aider</h2><strong><pre>    * <----- vous &ecirc;tes ici</pre></strong></body></html>
Run Code Online (Sandbox Code Playgroud)


hee*_*ayl 14

要将一行附加到文件,您可以只使用 shell 附加重定向运算符,>>(文件将被open(2)-edO_APPEND标志):

echo 'My final line' >>file.txt
Run Code Online (Sandbox Code Playgroud)

现在,如果您只想查看附加了最后一行的文件内容,我将使用cat两个参数:

  • 首先,你的文件很明显,让我们说 file.txt
  • 第二个参数是您选择的字符串,并将字符串作为文件名传递(因为cat仅处理文件),您可以利用进程替换, <(),这将返回文件描述符(/proc/self/fd/<fd_number>).

把这些放在一起:

cat file.txt <(echo 'My final line')
Run Code Online (Sandbox Code Playgroud)

如果您希望输出被分页,假设less是您最喜欢的寻呼机:

less file.txt <(echo 'My final line')
Run Code Online (Sandbox Code Playgroud)


Kat*_*atu 12

sed -e '$aMy final line' file.txt
Run Code Online (Sandbox Code Playgroud)

man sed选项-e

-e script, --expression=script
    add the script to the commands to be executed
Run Code Online (Sandbox Code Playgroud)

$匹配最后一行并 a附加字符串。

如果您想将该行永久附加到文件中,请使用 -i

-i[SUFFIX], --in-place[=SUFFIX]
    edit files in place (makes backup if SUFFIX supplied)
Run Code Online (Sandbox Code Playgroud)

将命令更改为

sed -i -e '$aMy final line' file.txt
Run Code Online (Sandbox Code Playgroud)


Paŭ*_*ann 8

问题的评论中已经澄清了这一点,但在此处再次添加作为答案。

问题中提到的命令,

(cat file.txt ; echo "My final line") | other command
Run Code Online (Sandbox Code Playgroud)

按预期工作 - 由括号形成的子shell的所有输出都通过管道传输到第二个命令。

如果文件没有以新行结尾,则回显字符串将附加到最后一行——这与此处的所有其他解决方案很常见,并且可以通过在之前添加另一个(空)回显来解决。