3

File A :

1
3
5
7

File B:

2
4
6
8

Is is possible to use File A and File B as input in a shell script and get an output which is File C whose contents are as follows:

1
2
3
4
5
6
7
8  
Jean
  • 20,165
  • 23
  • 64
  • 110
Amistad
  • 6,540
  • 11
  • 43
  • 71
  • possible duplicate of [How to interleave lines from two text files](http://stackoverflow.com/questions/4011814/how-to-interleave-lines-from-two-text-files) – John Kugelman Sep 03 '13 at 15:56

5 Answers5

9

Use paste to interleave the lines in the exact order they're found:

paste -d '\n' filea fileb

Or use sort to combine and sort the files:

sort filea fileb
John Kugelman
  • 330,190
  • 66
  • 504
  • 555
4

Simply:

sort -n FileA FileB > FileC

Gives:

1
2
3
4
5
6
7
8
fugu
  • 6,127
  • 4
  • 34
  • 73
  • this does not always work..my filenames are such that sorting it in alphabetical order does not fix it..John Kugelman's method is foolproof.. – Amistad Sep 03 '13 at 16:02
  • 1
    It's got nothing to do with the filenames – fugu Sep 03 '13 at 16:05
  • 1
    `sort -n FileB FileA > FileC` will give the same result. Though sticking a `-u` in there might also be a good idea. – dannysauer Sep 04 '13 at 04:10
2
$ cat > filea
1
3
5
7
$ cat > fileb
2
4
6
8 
$ sort -m filea fileb
1
2
3
4
5
6
7
8
$ 

just to make it clear... press ctrl D at the end of each list of numbers for setting up filea and fileb. Thanks Kevin

Vorsprung
  • 30,988
  • 4
  • 36
  • 58
1

Since you said you wanted a shell solution,

#!/bin/bash

if [ $# -ne 2 ] ; then
   echo 'usage: interleave filea fileb >out' >&2
   exit 1
fi

exec 3<"$1"
exec 4<"$2"

read -u 3 line_a
ok_a=$?

read -u 4 line_b
ok_b=$?

while [ $ok_a -eq 0 -a $ok_b -eq 0 ] ; do
   echo "$line_a"
   echo "$line_b"

   read -u 3 line_a
   ok_a=$?

   read -u 4 line_b
   ok_b=$?
done

if [ $ok_a -ne 0 -o $ok_b -ne 0 ] ; then
   echo 'Error: Inputs differ in length' >&2
   exit 1
fi
ikegami
  • 343,984
  • 15
  • 249
  • 495
0

If you want to append the second file contents at the end of first file.

cat file1.txt file2.txt > file3.txt