小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
主要介绍,除了echo、vi/vim添加内容到文件之外的其他方法,如cat、tee等命令。
cat命令加重定向
本质上还是利用的重定向符的作用!
cat是用于查看文件内容或将内容输出到标准输出的命令,即将内容输出的屏幕,并且可以翻页、滚动等形式查看。通过将其输出重定向到文件,同样可以实现添加内容到文件中。
使用输入开始结束标记(cat命令法)
# cat >> cat_test.txt <<EOF
> I am a test
> use cat >>(redirect-character)
> EOF
# cat cat_test.txt
I am a test
use cat >>(redirect-character)
其中的EOF要顶格写,并且成对出现,表示开始和结束。
EOF并不是一个特殊字符,可以使用任何其他成对的字符替代。
如下,使用AB、lnm作为开始、结束:
# cat >> cat_test.txt <<AB
> test begin and end
> AB
# cat cat_test.txt
I am a test
use cat >>(redirect-character)
test begin and end
# cat > cat_test.txt <<lmn
> new test
> lmn
# cat cat_test.txt
new test
直接回车输入编辑(cat编辑法)
cat >> file
或 cat > file
后直接回车,开始编辑输入内容,按Ctrl+d组合键结束编辑。
[root@VM_0_15_centos test]# cat > cat_test.txt
我是直接回车编辑的内容
需要crtl+d结束编辑[root@VM_0_15_centos test]# cat cat_test.txt
我是直接回车编辑的内容
需要crtl+d结束编辑[root@VM_0_15_centos test]#
tee命令
tee
是 Linux 中的命令行实用程序,它从标准输入读取数据,并同时写入标准输出和一个或多个文件。
默认情况下,tee 命令覆盖指定的文件。 要将输出附加到文件中,可以使用 tee 和 -a (--append)选项:
# echo "this is a new line" | tee -a file.txt
this is a new line
# cat file.txt
this is a new line
如果不希望 tee 写入标准输出,可以将其重定向到 /dev/null
:
# echo "this is a another line" | tee -a file.txt >/dev/null
# cat file.txt
this is a new line
this is a another line
使用tee命令,将文本追加到多个文件中:
echo "this is a new line has been appended to multiple files" | tee -a file1.txt file2.txt file3.txt