4

I have two files : called t1.txt and t2.txt. The contents are :

t1.txt

a
b
c

t2.txt

ab
bc
cd

Now I want to merge these two files line by line into t3.txt so that the t3.txt should look like :

t3.txt

aab
bbc
ccd

Please help in getting the output using shell script.

0

3 Answers 3

3

paste & sed

There are more efficient ways but here's a quick and dirty method using paste and sed.

$ paste -d":" t1.txt t2.txt | sed 's/://g'
aab
bbc
ccd

The above joins the 2 files like this:

a:ab
b:bc
c:cd

And the sed removes the :.

just paste

You can forgo using the sed, it's a bit redundant by telling paste to use nothing as a delimiter when joining the files:

$ paste -d "" t1.txt t2.txt
aab
bbc
ccd

awk

You can also use awk to do this:

$ awk 'NR==FNR{a[FNR]=$0;next} {print a[FNR] $0}'  t1.txt t2.txt
aab
bbc
ccd

This loops through the 1st file, t1.txt, and stores it in an array, a[FNR]. The FNR is the index into that array based on the line number each line was in, in file t1.txt. Afterwards, it loops through the 2nd file, t2.txt, and prints the line corresponding line from the 1st file along with the 2nd file.

join & awk & nl

This method is a little convoluted but works and makes the heavy lifting less complicated when using awk, in terms of what's going on.

$ join <(nl t1.txt) <(nl t2.txt)|awk '{print $2 $3}'
aab
bbc
ccd

The nl ... commands produce versions of the test files with line numbers:

$ nl t1.txt 
     1  a
     2  b
     3  c

The join command then uses these line numbers as the piece of data which is common to both files, so it can join on it.

$ join <(nl t1.txt) <(nl t2.txt)
1 a ab
2 b bc
3 c cd

The awk is used at the end to extract the 2nd and 3rd columns from above.

pr & awk

The little used pr command can also be used to join the files using its merge switch -m.

$ pr -t -m  t1.txt t2.txt  | awk '{print $1 $2}'
aab
bbc
ccd
2
  • paste -d '' is not portable Commented Aug 15, 2013 at 20:37
  • The join one will not work with many versions of join as join expects input lexically sorted on keys. Note that nl doesn't number every line. Commented Oct 30, 2014 at 15:43
1
paste -d '\0' t1.txt t2.txt > t3.txt

No it doesn't include NUL characters between the two files.

Yes, it is standard (POSIX) and portable, and the most efficient you can get.

0

From BASH shell try to run (without any additional text processing tools):

exec 3< t1.txt
exec 4< t2.txt

while read l1 <&3 && read l2 <&4; do
    echo ${l1}$l2
done > t3.txt
1
  • Note that it assumes the data contains no blank, wildcard or backslash characters, and lines don't start with -. It's also going to be terribly inefficient especially if using bash unless the files are small. Commented Aug 15, 2013 at 14:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .