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)
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是恒定的。
小智 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)
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 标记。
====================================