Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate every four files, Linux

I have two files stored with lists of file names:

FileA:
GSM1328513
GSM1328514
GSM1328515
GSM1328516
GSM1328545
GSM1328546
GSM1328547
GSM1328548
GSM1328609
GSM1328610
GSM1328611
GSM1328612

and:
FileB:
    Brn
    Hrt
    Lng 

What I want to do is, concatenate every four files listed in the fileA and name the concatenated file as the file names listed in fileB: To do it manually, it looks like:

cat GSM1328513 GSM1328514 GSM1328515 GSM1328516 > Brn
cat GSM1328545 GSM1328546 GSM1328547 GSM1328548 > Hrt
cat GSM1328609 GSM1328610 GSM1328611 GSM1328612 > Lng

Since I have a long list of files, I want to do it automatically, could anyone help. In case anything not clear, please point out.

like image 455
Jun Cheng Avatar asked Dec 08 '22 06:12

Jun Cheng


2 Answers

Another quick way to do it without sed:

cat FileA | while read a ; do read b ; read c ; read d ;
    echo "cat $a $b $c $d > " ; done | paste - FileB | bash

As Didier Trosset said, you can skip the | bash to see what it does before executing it.

Other approach: one-liner without eval, combining @dshepherd solution with mine:

cat FileA | xargs -n4 echo | paste - FileB | while read a b c d e ; do cat $a $b $c $d > $e ; done

Advantages: this is the only one-liner so far which does not eval any output (| bash) and does not use temporary files, and only uses standard tools found everywhere (cat, xargs, paste).

like image 171
Juan Cespedes Avatar answered Dec 11 '22 11:12

Juan Cespedes


Here is the Shell script to do what you want to do

iter=0
while read filename
do
    stop=`expr \( $iter + 1 \) \* 4`
    iter=`expr $iter + 1`
    files=`head -n $stop fileA | tail -n 4 | tr '\n' ' '`
    cat $files > $filename
done < fileB
like image 21
nisargjhaveri Avatar answered Dec 11 '22 12:12

nisargjhaveri