如何将多行附加到文件

The*_*end 460 shell io-redirection text-processing

我正在编写一个 bash 脚本来查找不存在的文件,然后创建它并将其附加到它:

Host localhost
    ForwardAgent yes
Run Code Online (Sandbox Code Playgroud)

所以"line then new line 'tab' then text"我认为它是一种敏感的格式。我知道你可以这样做:

cat temp.txt >> data.txt
Run Code Online (Sandbox Code Playgroud)

但它看起来很奇怪,因为它有两行。有没有办法以这种格式附加它:

echo "hello" >> greetings.txt
Run Code Online (Sandbox Code Playgroud)

Hau*_*ing 804

# possibility 1:
echo "line 1" >> greetings.txt
echo "line 2" >> greetings.txt

# possibility 2:
echo "line 1
line 2" >> greetings.txt

# possibility 3:
cat <<EOT >> greetings.txt
line 1
line 2
EOT
Run Code Online (Sandbox Code Playgroud)

如果需要 sudo(其他用户权限)来写入文件,请使用以下命令:

# possibility 1:
echo "line 1" | sudo tee -a greetings.txt > /dev/null

# possibility 3:
sudo tee -a greetings.txt > /dev/null <<EOT
line 1
line 2
EOT
Run Code Online (Sandbox Code Playgroud)

  • @cikatomo 在`cat &lt;&lt;EOT` 中,`EOT` 只是一个随机字符串。也可以是`cat &lt;&lt;FOO`。 (23认同)
  • @TheLegend 这被称为“此处的文档”。看看手册页中的那一段。 (8认同)
  • @ott--您不需要真正的子shell(即可以保存一个新进程),这就足够了:`{ echo "line 1" ; 回声“第2行”;} &gt;&gt;问候.txt` (6认同)
  • 另一种可能性是`( echo "line 1" ; echo "line 2" ) &gt;&gt;greetings.txt`。 (3认同)
  • EOT 和 EOL 有什么区别? (3认同)
  • @cikatomo fyi,“EOT、EOL、EOF”首字母缩写词分别代表“传输结束/线路/文件” (3认同)
  • @TCB13 `cat &lt;&lt;"EOT" ... EOT` 防止参数和 shell 变量的扩展。 (2认同)

evi*_*oup 72

printf '%s\n    %s\n' 'Host localhost' 'ForwardAgent yes' >> file.txt
Run Code Online (Sandbox Code Playgroud)

或者,如果它是您想要的文字选项卡(而不是您问题中的四个空格):

printf '%s\n\t%s\n' 'Host localhost' 'ForwardAgent yes' >> file.txt
Run Code Online (Sandbox Code Playgroud)

您可以使用 实现相同的效果echo,但具体如何因实现而异,而printf是恒定的。


小智 65

echo -e "Hello \nWorld \n" >> greetings.txt
Run Code Online (Sandbox Code Playgroud)


小智 38

另一种方法是使用 tee

tee -a ~/.ssh/config << END
Host localhost
  ForwardAgent yes
END
Run Code Online (Sandbox Code Playgroud)

tee的手册页中的一些选择行:

tee 实用程序将标准输入复制到标准输出,在零个或多个文件中进行复制。

-a - 将输出附加到文件而不是覆盖它们。


小智 19

这是在文件中附加多行的示例:

{
        echo '  directory "/var/cache/bind";'
        echo '  listen-on { 127.0.0.1; };'
        echo '  listen-on-v6 { none; };'
        echo '  version "";'
        echo '  auth-nxdomain no;'
        echo '  forward only;'  
        echo '  forwarders { 8.8.8.8; 8.8.4.4; };'
        echo '  dnssec-enable no;'
        echo '  dnssec-validation no;'
} >> your_file.txt
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,这个变体是 ShellCheck 推荐的一部分 https://github.com/koalaman/shellcheck/wiki/SC2129 (2认同)

OB7*_*DEV 7

SED 可以像这样在文件末尾附加一行:

sed -i '$ a text to be inserted' fileName.file
$选择文件末尾,a告诉它附加,然后是要插入的文本。然后当然是文件名。


来源:http : //www.yourownlinux.com/2015/04/sed-command-in-linux-append-and-insert-lines-to-file.html

==========EDIT== ==========

这种方法比其他解决方案有什么额外的好处吗?
是的,这种方法具有附加到搜索中返回的任何文件的额外好处,例如: find . -name "*.html" -exec sed -i '$ a </html>' {} \;

我使用上面的示例插入了许多目录中每个 html 页面上缺少的结束 html 标记。

====================================