Tuesday, January 8, 2008

Formatting - AWK digest


Suppose I got 3 files of contents like below:

$ cat filex

1|100
2|200
3|300
4|400
5|500

$ cat filey

1|200
2|200
3|600
4|800

$ cat filez

1|300
2|100
3|200

Required Output:

1|100|200|300|0
2|200|200|100|300
3|300|600|200|700
4|400|800|0|1200
5|500|0|0|500

i.e. if
f1=filex.column2
f2=filey.cloumn2
f3=filez.cloumn2

then the output required is :

1|f1|f2|f3|f1+f2-f3
2|f1|f2|f3|f1+f2-f3
....
....

My Solution:

$ paste -d "|" filex filey filez | awk '
> BEGIN{OFS=FS="|"} {print $1,$2,$4,$6,$2+$4-$6}
> ' | awk 'BEGIN{OFS=FS="|"}{ for(i=0;i<=NF;i++)
> if ( $i == "" )
> $i=0
> print $0}'

2 comments:

priyanka said...

Hi

I have a file like This
file1.txt
aa
bb
cc
dd
ee

file2.txt
aa 1
cc 2
dd 1

I want output like this
aa 1
bb 0
cc 2
dd 1
ee 0

priyanka said...

i have a file like this
file1.txt
aa
bb
cc
dd
file2.txt
aa 1
cc 2
ee 2

output required

aa 1
bb 0
cc 2
dd 0
ee 2

© Jadu Saikia www.UNIXCL.com