merging contents from two files in one file using shell script

14,242

Solution 1

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

Solution 2

Simply:

sort -n FileA FileB > FileC

Gives:

1
2
3
4
5
6
7
8

Solution 3

$ 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

Solution 4

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
Share:
14,242

Related videos on Youtube

Amistad
Author by

Amistad

Updated on September 04, 2022

Comments

  • Amistad
    Amistad over 1 year

    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  
    
  • Kevin
    Kevin over 10 years
    Your first two commands are going to hang forever. You should get rid of the redirect.
  • Vorsprung
    Vorsprung over 10 years
    Kevin, yes of course. There is an invisible ctrl-D happening!
  • Amistad
    Amistad over 10 years
    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..
  • fugu
    fugu over 10 years
    It's got nothing to do with the filenames
  • dannysauer
    dannysauer over 10 years
    sort -n FileB FileA > FileC will give the same result. Though sticking a -u in there might also be a good idea.