Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating text files in bash

Tags:

bash

I have many text files with only one line float value in one folder and I would like to concatenate them in bash in order for example: file_1.txt, file_2.txt ...file_N.txt. I would like to have them in one txt file in the order from 1 to N. Could someone please help me ? Here is the code I have but it just concatenates them in random manner. Thank you

for file in *.txt
do 
  cat ${file} >>  output.txt  
done 
like image 479
user3612121 Avatar asked Mar 14 '26 09:03

user3612121


2 Answers

As much as I recommend against parsing the output of ls, here we go.

ls has a "version sort" option that will sort numbered files like you want. See below for a demo.

To concatenate, you want:

ls -v file*.txt | xargs cat > output
$ touch file{1..20}.txt
$ ls
file1.txt   file12.txt  file15.txt  file18.txt  file20.txt  file5.txt  file8.txt
file10.txt  file13.txt  file16.txt  file19.txt  file3.txt   file6.txt  file9.txt
file11.txt  file14.txt  file17.txt  file2.txt   file4.txt   file7.txt
$ ls -1
file1.txt
file10.txt
file11.txt
file12.txt
file13.txt
file14.txt
file15.txt
file16.txt
file17.txt
file18.txt
file19.txt
file2.txt
file20.txt
file3.txt
file4.txt
file5.txt
file6.txt
file7.txt
file8.txt
file9.txt
$ ls -1v
file1.txt
file2.txt
file3.txt
file4.txt
file5.txt
file6.txt
file7.txt
file8.txt
file9.txt
file10.txt
file11.txt
file12.txt
file13.txt
file14.txt
file15.txt
file16.txt
file17.txt
file18.txt
file19.txt
file20.txt
like image 114
glenn jackman Avatar answered Mar 16 '26 00:03

glenn jackman


for file in *.txt
do 
  cat ${file} >>  output.txt  
done 

This works for me as well as :

for file in *.txt
do 
  cat $file >>  output.txt  
done

You don't need {}

But the simpler is still :

cat file*.txt > output.txt

So if you have more than 9 files as suggested in the comment, you can do one of the following :

files=$(ls file*txt | sort -t"_" -k2g)
files=$(find . -name "file*txt" | sort -t "_" -k2g)
files=$(printf "%s\n" file_*.txt | sort -k1.6n) # Thanks to glenn jackman

and then:

cat $files

or

cat $(find . -name "file*txt" | sort -t "_" -k2g)

Best is still to number your files correctly, so file_01.txt if you have less than 100 files, et file_001.txt if less than 1000, an so on.


example :

ls file*txt
file_1.txt  file_2.txt  file_3.txt  file_4.txt  file_5.txt  file_10.txt

They contain only their corresponding number.

$ cat $files
1
2
3
4
5
10
like image 37
jrjc Avatar answered Mar 15 '26 22:03

jrjc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!