Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
In addition to echo, vi/vim to add content to the file other methods, such as cat, tee and other commands.
The cat command aggravates the direction
Essentially the use of redirection character role!
Cat is a command used to view the contents of a file or output the content to standard output, that is, the output screen of the content, and can be viewed in the form of page flipping, scrolling, etc. You can also add content to a file by redirecting its output to a file.
Use the input start/end flag (cat command)
# 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)
Copy the code
The EOF should be written top and in pairs, indicating the beginning and end.
EOF is not a special character and can be replaced with any other paired character.
Start and end with AB and LNM as follows:
# 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
Copy the code
Enter to edit (CAT editing)
After cat >> file or cat > File, press Enter to edit the input content, and press Ctrl+ D to finish editing.
[root@VM_0_15_centos test]# cat > cat_test.txtI am directly enter to edit the content requires CRTL + D to end the edit [root@VM_0_15_centostest]# cat cat_test.txtI am directly enter to edit the content requires CRTL + D to end the edit [root@VM_0_15_centostest]#
Copy the code
The tee command
Tee is a command-line utility in Linux that reads from standard input and writes to standard output and one or more files simultaneously.
By default, the tee command overwrites the specified file. To append output to a file, use tee and -a (–append) options:
# echo "this is a new line" | tee -a file.txt
this is a new line
# cat file.txt
this is a new line
Copy the code
If you don’t want tee to write to standard output, you can redirect it to /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
Copy the code
Use the tee command to append text to multiple files:
echo "this is a new line has been appended to multiple files" | tee -a file1.txt file2.txt file3.txt
Copy the code
reference
- Several ways Linux adds content to files
- Common Linux command 05 – text appended to the file