Friday, August 1, 2014

Mingle multiple files with awk

$ echo -en {a..i}"\n"|sed 's/^[a-z]/ &/g;s/./& & & &/g'>file1;cat file1
       a a a a
       b b b b
       c c c c
       d d d d
       e e e e
       f f f f
       g g g g
       h h h h
       i i i i
$ echo -en {9..1}"\n"|sed 's/^[0-9]/ &/g;s/./& & & &/g'>file2;cat file2
       9 9 9 9
       8 8 8 8
       7 7 7 7
       6 6 6 6
       5 5 5 5
       4 4 4 4
       3 3 3 3
       2 2 2 2
       1 1 1 1

$ awk 'FNR==NR {a[FNR]=$0; next}{print a[FNR]"\n"$0}' file1 file2 
       a a a a
       9 9 9 9
       b b b b
       8 8 8 8
       c c c c
       7 7 7 7
       d d d d
       6 6 6 6
       e e e e
       5 5 5 5
       f f f f
       4 4 4 4
       g g g g
       3 3 3 3
       h h h h
       2 2 2 2
       i i i i
       1 1 1 1
$ awk 'FNR==NR {a[FNR]=$0; next}{print a[FNR] $0}' file1 file2 
       a a a a       9 9 9 9
       b b b b       8 8 8 8
       c c c c       7 7 7 7
       d d d d       6 6 6 6
       e e e e       5 5 5 5
       f f f f       4 4 4 4
       g g g g       3 3 3 3
       h h h h       2 2 2 2
       i i i i       1 1 1 1 
or for three or more files:  
$ awk 'FILENAME==ARGV[1]{a[FNR]=$0;next}FILENAME==ARGV[2]{b[FNR]=$0;next}FILENAME==ARGV[3]{print a[FNR] b[FNR] $0}' file1 file2 file3
       a a a a       9 9 9 9       1 1 1 1
       b b b b       8 8 8 8       2 2 2 2
       c c c c       7 7 7 7       3 3 3 3
       d d d d       6 6 6 6       4 4 4 4
       e e e e       5 5 5 5       5 5 5 5
       f f f f       4 4 4 4       6 6 6 6
       g g g g       3 3 3 3       7 7 7 7
       h h h h       2 2 2 2       8 8 8 8
       i i i i       1 1 1 1       9 9 9 9
 of course if thats all you need you could use: 
$ paste file1 file2 file3 
       a a a a        9 9 9 9        1 1 1 1
       b b b b        8 8 8 8        2 2 2 2
       c c c c        7 7 7 7        3 3 3 3
       d d d d        6 6 6 6        4 4 4 4
       e e e e        5 5 5 5        5 5 5 5
       f f f f        4 4 4 4        6 6 6 6
       g g g g        3 3 3 3        7 7 7 7
       h h h h        2 2 2 2        8 8 8 8
       i i i i        1 1 1 1        9 9 9 9
yet the awk way gives much more flexibility and possibilities  

No comments:

Post a Comment