ann*_*hri 13 shell shell-script
我总是这样做来将文本附加到文件中
echo "text text text ..." >> file
# or
printf "%s\n" "text text text ..." >> file
Run Code Online (Sandbox Code Playgroud)
我想知道是否有更多方法可以实现相同、更优雅或更不寻常的方式。
roa*_*ima 24
我非常喜欢这个,我可以在脚本顶部设置一个日志文件并在整个过程中写入它,而无需全局变量或记住更改所有出现的文件名:
exec 3>> /tmp/somefile.log
...
echo "This is a log message" >&3
echo "This goes to stdout"
echo "This is written to stderr" >&2
Run Code Online (Sandbox Code Playgroud)
该exec 3>dest
构造打开文件dest
进行写入(>>
用于追加、<
读取 - 就像往常一样)并将其附加到文件描述符 #3。然后,您将获得stdout 的#1 描述符、stderr 的#2以及文件的新#3 dest
。
您可以在脚本运行期间将stderr连接到stdout,例如exec 2>&1
- 有很多强大的可能性。文档 ( man bash
) 有这样的说法:
exec [-cl] [-a name] [command [arguments]]
如果command
指定,它将替换外壳。[...]如果command
未指定,任何重定向都会在当前 shell 中生效 [...]。
小智 12
以下是将文本附加到文件的其他几种方法。
使用三通
tee -a file <<< "text text text ..."
Run Code Online (Sandbox Code Playgroud)使用 awk
awk 'BEGIN{ printf "text text text ..." >> "file" }'
Run Code Online (Sandbox Code Playgroud)使用 sed
sed -i '$a text text text ...' file
sed -i -e "\$atext text text ..." file
Run Code Online (Sandbox Code Playgroud)资料来源:
Pau*_*omé 10
使用here-document
方法:
cat <<EOF >> file
> foo
> bar
> baz
> EOF
Run Code Online (Sandbox Code Playgroud)
测试:
$ cat file
aaaa
bbbb
$ cat <<EOF >> file
> foo
> bar
> baz
> EOF
$ cat file
aaaa
bbbb
foo
bar
baz
Run Code Online (Sandbox Code Playgroud)
请参阅dd(1)手册页:
dd conv=notrunc oflags=append bs=4096 if=myNewData of=myOldFile
Run Code Online (Sandbox Code Playgroud)