我有一个要求,如果满足特定条件,我需要将文件的全部内容复制到同一个文件中。这是文件:
$ cat in.txt
ip
10.22.1.34
10.22.1.35
Run Code Online (Sandbox Code Playgroud)
当满足某个条件时,例如
if [[ d=1 ]]; then
copy the file content
fi
Run Code Online (Sandbox Code Playgroud)
文件的内容应复制如下:
ip
10.22.1.34
10.22.1.35
ip
10.22.1.34
10.22.1.35
Run Code Online (Sandbox Code Playgroud)
您可以将文件内容存储到变量中(它将存储换行符),然后从变量附加到同一文件。只需记住在变量周围使用引号即可。
x=$(cat test.txt) && echo "$x" >> test.txt
Run Code Online (Sandbox Code Playgroud)
或者使用“tee”命令,您可以直接附加到同一个文件,当它第一次在标准输出中显示文件原始内容时不要感到困惑,它同时复制了文件的实际内容。
cat test.txt | tee -a test.txt
Run Code Online (Sandbox Code Playgroud)
如果您不希望 tee 的输出可见,您当然可以这样做:
cat test.txt | tee -a test.txt > /dev/null
Run Code Online (Sandbox Code Playgroud)