合并两个文件并使用 cat 覆盖原始文件

combine two files and overwrite original file using cat

我尝试使用 cat 命令合并两个文件,但遇到了问题。

original.txt
============ 
foo
bar
foo
bar

以下是我的脚本。

cat original.txt | wc -l > linecount.txt | cat linecount.txt original.txt > original.txt

此脚本 returns 错误显示 "input file and output file is the same."。

预期结果是这样的

original.txt
============
4
foo
bar
foo
bar

有什么想法吗?

你或许可以使用:

{ wc -l < original.txt; cat original.txt; } > linecount.txt &&
mv linecount.txt original.txt

或使用awk:

awk 'NR==FNR{++n; next} FNR==1{print n} 1' original.txt{,} > linecount.txt &&
mv linecount.txt original.txt

或者:

awk -v n=$(wc -l < original.txt) 'NR==1{print n} 1' original.txt > linecount.txt &&
mv linecount.txt original.txt 

您可以使用 sponge from the moreutils 包。我喜欢它:

cat <(wc -l orig.txt) orig.txt | sponge orig.txt

如果你没有sponge或无法安装它,你可以用awk实现它作为bash功能:

function sponge() {
    awk -v o="" '{b=NR>1?b""ORS""[=11=]:[=11=]}END{print b > o}'
}

请记住,这需要将整个文件存储在内存中。不要将它用于非常大的文件。