Concatenate every four files, Linux Concatenate every four files, Linux bash bash

Concatenate every four files, Linux


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).


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

iter=0while read filenamedo    stop=`expr \( $iter + 1 \) \* 4`    iter=`expr $iter + 1`    files=`head -n $stop fileA | tail -n 4 | tr '\n' ' '`    cat $files > $filenamedone < fileB


Another approach: you can easily generate groups of four filenames using

cat FileA | xargs -n4 echo

However I can't think of any especially elegant way to combine this with the output filenames from FileB. One possibility is to do some string manipulation then eval it (like Didier Trosset's answer).

Edit: got it! Using GNU parallel (which is like xargs on steroids):

parallel < tempA -n4 -k --files cat | paste - tempB | xargs -n 2 mv

the parallel command runs cat on each group of 4 arguments and puts the output into temp files. It writes the names of these temp files to stdout (and -k means they are written out in the correct order).

paste inserts the desired filenames into the stream, then we just use xargs -n 2 mv to move the temp files to the desired locations.

I used < tempA instead of cat tempA because it's technically best practice.

The advantage (in my opinion) of this over the other one liners is that you don't have to eval strings (e.g. using bash).