In Linux, if I have a bunch of text files is there a simple script to merge them into one file?
For example suppose I have 1.csv, 2.c开发者_Python百科sv, ... , 20.csv. Is there a simple shell script where I can merge everything into merged.csv?
Use cat to concatenate them.
cat *.csv > merged.csv
As @sarnold points out this will concatenate them out of order. If that's important, use his for loop suggestion, or this xargs pipeline:
ls *.csv | sort -n | xargs cat > merged.csv
If you're looking to merge files by appending the lines from one on to the end of the lines of the other, then you're looking for paste
.
For example, if file1 contains:
1,One
2,Two
And file2 contains:
A,B,C
D,E,F
You could run paste -d , file1 file2
to get this:
1,One,A,B,C
2,Two,D,E,F
The simple answer:
cat *.csv > merged.csv
will sort 1.csv 10.csv 2.csv 20.csv 3.csv...
. If you want them sorted by number, it takes a bit more work:
for i in `seq 1 20`; do cat ${i}.csv >> merged.csv ; done
cat {1..20}.csv > merged.csv
It's what cat was made for! Note that I've used a bash-ism in the {1..20}
sequence.
精彩评论