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