-1

I have a list of files as follow:

a1.txt
a2.txt
b1.txt
b2.txt
c1.txt
c2.txt
...
z1.txt
z2.txt

I wonder how could I write command to merge the first two files a1.txt + a2.txt and output as a.zip and similarly, b1.txt + b2.txt to output b.zip, c1.txt + c2.txt to output c.zip, etc.

Thanks for your kind help!

jww
  • 97,681
  • 90
  • 411
  • 885
Hà Hoàng
  • 11
  • 3
  • 1
    Possible duplicate of [Looping through alphabets in Bash](https://stackoverflow.com/q/7300070/608639): `for x in {a..z}; do ... done`. – jww Dec 25 '19 at 11:56
  • Try writing a loop that reads one line at a time and outputs just one file. If you can get that working, try modifying it to read two lines at a time. – Iguananaut Dec 25 '19 at 12:17

1 Answers1

1

If you don't want to merge the file contents and just put them into the same zip-file if their names start with the same letter, you can just run

for c in {a..z}; do zip "$c".zip "$c"*.txt; done

If you want to merge your a-files, b-files etc. first and then zip the merged version, you can run

for c in {a..z}; do cat "$c"1.txt "$c"2.txt > "$c".txt ;zip "$c".zip "$c".txt; done

Note that this creates zips for all letters from a to z, if you just need a subset, e.g. a-f, you can iterate over {a..f} only.

ctenar
  • 718
  • 5
  • 24
  • Hi,Thanks for your help. Actually, my list of files is not in the form a.txt, b.txt... z.txt, I am just trying to simplify it. How could I handle the problem if the files name are like: abc1.txt, abc2.txt, ijk1.txt, ijk2.txt, etc. Thanks – Hà Hoàng Dec 25 '19 at 16:09
  • If you want to concatenate the contents from abc1.txt and abc2.txt etc., you coud iterate over all prefix patterns like this, for instance: ```for file in `ls *1.txt`; do pref=`echo $file | cut -d'1' -f1`; file2="${pref}2.txt"; cat "$file" "$file2" > "${pref}.txt"; done``` Just replace the line ```cat "$file" "$file2" > "${pref}.txt"``` by what you actually want to do with your files. – ctenar Dec 25 '19 at 18:34