Monday, March 10, 2008

Merge alternate lines of files - BASH,AWK


$ cat file1
AAAA
BBBB
CCCC
DDDD
EEEE
FFFF


$ cat file2
1111
2222
3333
4444
5555
6666


Required Output:
AAAA
1111
BBBB
2222
CCCC
3333
DDDD
4444
EEEE
5555
FFFF
6666

$ cat file2 | paste - | paste file1 - | tr "\t" "\n"
$ paste file1 file2 | tr '\t' '\n'


Now suppose,
$ cat file1
AAAA
BBBB
CCCC


and file2 is as mentioned above.
and you want to merge file1 and file2 such that for every line of file1, two lines of file2 should follow.
i.e.

AAAA
1111
2222

BBBB
3333
4444

CCCC
5555
6666


This can be achieved:

$ cat file2 | paste - - | paste file1 - | tr "\t" "\n"

And using AWK:

$ awk 'FNR==NR{ a[FNR]=$0;next }
{
print $0
print a[FNR+l]
l++
print a[FNR+l]
}
' file2 file1


Note: FNR is the current record number in the current file. FNR is incremented each time a new record is read.It is reinitialized to zero each time a new input file is started.

4 comments:

Unknown said...

One more:

$ cat file1
a
b
c
d
e

$ cat file2
1
2
3
4
5

$ awk 'FNR==NR{ a[FNR]=$0;next }
{
print $0
print a[FNR+l]
}
' file2 file1
a
1
b
2
c
3
d
4
e
5

tiga2001 said...

thanks for posting this up. This is like magic

hieeee said...

What if i have to interleave 'm' lines from 'n' files?

Unknown said...


sed -e 's/.*/[&]/' file1.txt |
dc -e "
$(< file2.txt sed -e 's/.*/[&]/')
[q]sq
[SM z 0 <a]sa #macro to store whole file2 in stack M
[? z 0 =q pLMp c l?x]s? #change LMp to LMpLMp for grabbing two lines from file2
lax l?x
"

© Jadu Saikia www.UNIXCL.com