Input files:
$ cat fileA.txt
Name:Age:BG:Country:Class
Jack:12:A+:JP:v
Neel:13:O+:IN:vi
Ani:11:A+:US:v
Loua:10:A+:US:iv
$ cat fileB.txt
Sex:Rank:FavS
M:2:Maths
M:3:Maths
F:1:English
F:4:Maths
Required: Replace column 4 (Country) of fileA.txt with 2nd column(Rank) of fileB.txt; so the required output:
Name:Age:BG:Rank:Class
Jack:12:A+:2:v
Neel:13:O+:3:vi
Ani:11:A+:1:v
Loua:10:A+:4:iv
$ awk '
BEGIN {FS=OFS=":"}
NR == FNR {
a[FNR] = $B
next
}
$A = a[FNR]
' B=2 A=4 fileB.txt fileA.txt
Output:
Name:Age:BG:Rank:Class
Jack:12:A+:2:v
Neel:13:O+:3:vi
Ani:11:A+:1:v
Loua:10:A+:4:iv
Another solution (using paste) would be:
$ paste -d : fileA.txt fileB.txt | awk 'BEGIN {FS=OFS=":"} {print $1,$2,$3,$6}'
Name:Age:BG:Sex
Jack:12:A+:M
Neel:13:O+:M
Ani:11:A+:F
Loua:10:A+:F
Related post:
- Remove or delete a column using awk
- awk FNR variable usage example
Dedicated to all BASH newbies and Linux one liner lovers. Useful AWK,SED,BASH one liners.
Thursday, December 4, 2008
Replace column with column of another file awk
Subscribe to:
Post Comments (Atom)
© Jadu Saikia http://unstableme.blogspot.com

0 comments:
Post a Comment