ganesh_patil
ganesh_patil

Reputation: 3

Updating columns in unix

Need Unix code or script which will provide following results:

Suppose file 1 has following data

ABC 1 cvb
DEF 2. bnm

And file 2 has following data

ABC 3
DEF 4

The output file should contain data like

ABC 3 cvb
DEF 4 bnm

Upvotes: 0

Views: 204

Answers (1)

James Brown
James Brown

Reputation: 37394

Using awk:

$ awk 'NR==FNR{a[$1]=$2;next}{$2=a[$1];print}' file2 file1
ABC 3 cvb
DEF 4 bnm

Explained:

awk '            # using awk
NR==FNR {        # process first file
    a[$1]=$2     # hash to a on first field
    next         # next record
}
{                # process second file
    $2=a[$1]     # update second field from a hash
    print        # output
}' file2 file1   # mind the order of files

Upvotes: 2

Related Questions