如何将命令的输出附加到文本文件的末尾?
当前回答
我建议你做两件事:
在shell脚本中使用>>将内容附加到特定文件。文件名可以固定,也可以使用某种模式。 设置一个每小时一次的cronjob来触发shell脚本
其他回答
当指向文件输出时,使用>>而不是>:
your_command >> file_to_append_to
如果file_to_append_to不存在,则创建该文件。
例子:
$ echo "hello" > file
$ echo "world" >> file
$ cat file
hello
world
例如,你的文件包含:
1. mangesh@001:~$ cat output.txt
1
2
EOF
如果你想在文件末尾追加,那么---->记住'text' >> 'filename'之间的空格
2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt
1
2
EOF
somthing to append
和覆盖文件的内容:
3. mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx
somthing new to write
我经常把两者混淆。最好通过它们的输出来记住:
>表示覆盖
$ touch someFile.txt
$ echo ">" > someFile.txt
$ cat someFile.txt
>
$ echo ">" > someFile.txt
$ cat someFile.txt
>
>>表示追加
$ echo ">" > someFile.txt
$ cat someFile.txt
>
$ echo ">" >> someFile.txt
$ cat someFile.txt
>>
要追加一个文件,请使用>>
echo "hello world" >> read.txt
cat read.txt
echo "hello siva" >> read.txt
cat read.txt
那么输出应该是
hello world # from 1st echo command
hello world # from 2nd echo command
hello siva
要覆盖文件,请使用>
echo "hello tom" > read.txt
cat read.txt
那么输出是
你好,汤姆
对于整个问题:
cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
这将在o.txt中追加720行(30*24),之后将根据当前日期重命名文件。
每小时用cron运行上面的程序,或者
while :
do
cmd >> o.txt && [[ $(wc -l <o.txt) -eq 720 ]] && mv o.txt $(date +%F).o.txt
sleep 3600
done