Paste linux script
I have a small question and I will be grateful for your help.
I need to concatenate different text files together using the paste command:
paste -d, ~/Desktop/*.txt > ~/Desktop/Out/merge.txt
However, the files were leaked out of order. (text files are numbered 1, 2, 3, etc.)
I use *.txt
as there are different number of files for different scenarios.
Could you please help me with this.
source to share
If you are using modern bash you can write:
paste -d, ~/Desktop/{1..10}.txt > ~/Desktop/Out/merge.txt
If not, you should use something like:
paste -d, $(seq 1 10 | sed 's@.*@~/Desktop/&.txt) > ~/Desktop/Out/merge.txt
If you don't know what files you have in the directory, you can list and sort them:
cd ~/Desktop/
paste -d, $(ls -1d *.txt| sort -n) > ~/Desktop/Out/merge.txt
Example:
$ touch {1..20}.txt
$ echo $(ls -1 | sort -n)
1.txt 2.txt 3.txt 4.txt 5.txt 6.txt 7.txt 8.txt 9.txt 10.txt 11.txt 12.txt 13.txt 14.txt 15.txt 16.txt 17.txt 18.txt 19.txt 20.txt
Example 2:
$ echo hello > 1.txt
$ echo dear > 5.txt
$ echo friend > 11.txt
$ paste -d, $(ls -1d *.txt| sort -n)
hello,dear,friend
source to share
paste -d, $(ls ~/Desktop/*.txt) > ~/Desktop/Out/merge.txt
* Replaced by an alphabetically sorted list of your directory's filenames.
3.5.8 File name extension
Bash scans every word for '*,'? and '[. If one of these characters appears, that word is treated as a pattern and is replaced with an alphabetically sorted list of filenames matching the pattern.
So, the filename doesn't have to be sequential;)
source to share