简体   繁体   中英

combine two files and overwrite original file using cat

I try to combine two files using cat command, but facing a problem.

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

following is my script.

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

This script returns error that says "input file and output file is the same.".

Expected result is like this.

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

Any idea?

You can probably use:

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

Or using awk :

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

Or:

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

You can use sponge from the moreutils package. I like it for that:

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

If you don't have sponge or cannot install it, you can implement it with awk as a bash function:

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

Keep in mind that this will need to store the whole file in memory. Don't use it for very large files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM