Search code examples
bashwhile-loopheadtail

Merging 2 files with the head and tail utilities in bash


My two input files are as follows:

new

111
222
333

old

555
666

I want to merge them to get the following output

111
555
222
666
333

This is what I've tried so far

i=1
while read line
do
   head -$i $1 | tail -1
   head -$i $2 | tail -1 
   i=$(($i+1));
done < $1

This is the output I receive

111
555
222
666
333
666

How do I prevent it from taking the last line in 'old' twice? It should also be able to merge the two files if the second file is larger than the first.


Solution

  • You should just use paste:

    paste -d"\n" /tmp/file1 /tmp/file2