?

Log in

Previous Entry | Next Entry

#!/bin/bash
awk 'BEGIN{
    #set input/output field separator 
    OFS=FS="|"
}
FNR==NR{
    #get file2 contents to array
    #use first column as key and the 2nd column as value
    array[$1]=$2
    next
}
{
   #change the value of field 6 with that from file2 2nd column value
   if ($5 in array ) {    $6=array[$5]    }   
   print 
}' file2 file1


Usage:
Sample File1:
a|b|c|d|123|xxx
e|f|g|h|456|yyy
i|j|k|l|789|zzz

Sample File2:
456|what is this
123|this is it

Task: To replace 6th column of File1 ("|" as delimiter") with 2nd column of File2 using column 5(File1) and column1(File2) as keys.
 Output when run 
# ./myrepl.sh
a|b|c|d|123|this is it
e|f|g|h|456|what is this
i|j|k|l|789|zzz

Comments

( 2 comments — Leave a comment )
(Anonymous)
Jul. 20th, 2009 09:51 am (UTC)
fixed file
Great script ghostdog!
How would this script need to be modified to work with fixed file format in file1, while file2's format remains unchanged? Say I want to search characters 90-109 from file1 in file2 and overwrite characters 522-556 in file 1 with second column from file2.
Additional challenge:
file1 may contain leading zeros and blanks, whereas keys in file1 only contain numbers - still matching should work, e.g.:
file1 characters 90-109
00010103601
file2 key:
10103601;that's the way it is;

although reading man i still couldn't figure out how you handle both files differently - what's behind the FNR==NR trick?
thanks for your comments
best regards
guenther
ghostdog74
Jul. 21st, 2009 01:21 am (UTC)
Re: fixed file
want to show your input files samples? i work well with examples.
FNR means record number of current input file
NR means total number of records seen so far...
therefore FNR==NR basically means getting the records from current file. (notice i passed 2 files into awk ? )
( 2 comments — Leave a comment )

Profile

ghostdog74
ghostdog74

Latest Month

November 2013
S M T W T F S
     12
3456789
10111213141516
17181920212223
24252627282930

Tags

Page Summary

Powered by LiveJournal.com
Designed by Lilia Ahner