How to compare a file w.r.t a keyword file and replace mismatch strings of column 3 with correct string in column 3 of keyword file

Viewed 50

I want to search every line of search_file in keyword_file and print an output_file replacing the incorrect string of the line with the correct string extracted from keyword_file. Also, should warn the user if there are few entries with missing 3rd column, which do not exist in keyword_file and have in search_file (for example, "ggg coms" in the file)

Note, here keyword_file may contain an unequal number of line compared to search_file. For example: search_file

aaa coms 123
bbb coms 234
ccc 
ddd coms 456
eez coms 789
fkk coms 987
ggg coms   
hhh coms 989
....

keyword_file

aaa coms 789
bbb coms 234
ccc coms 878
ddd coms 456
ttt coms 654 
eee coms 789

Output

aaa coms 789
bbb coms 234
ccc coms 878
ddd coms 456
eez coms 789
fkk coms 987
hhh coms 989
....

I tried the following awk command, but it was not able to retain column #1 entries of search_file in the Output.

awk 'FNR==NR{a[$1]=$0} FNR!=NR&&a[$1]{print $1,$2,$3}' search_file keyword_file

Thank you in advanced for your help :)

1 Answers

Could you please try following, written and tested based on shown samples only.

awk '
{
  key=$1
}
FNR==NR{
  a[key]=$3
  next
}
(key in a){
  $0=key OFS $2 OFS a[key]
}
1
'  keyword_file  search_file

Explanation: Adding detailed explanation for above.

awk '                                ##Starting awk program from here.
{
  key=$1                             ##Run this command on each line of Input_file and create variable key with value of 1st field.
}
FNR==NR{                             ##Checking condition if FNR==NR which will be TRUE when keyword_file is being read.
  a[key]=$3                          ##Creating array a with index key and value of 3rd field here.
  next                               ##next will skip all further statements from here.
}
(key in a){                          ##Checking condition if key is present in array a then do following.
  $0=key OFS $2 OFS a[key]           ##Setting value of key OFS 2nd field OFS array a value with index key here.
}
1                                    ##1 will print edited/non-edited values for all lines.
'  keyword_file  search_file         ##Mentioning Input_file names here.

Why OP's code didn't work: You were close you only printed lines where first and second fields are common in both the Input_files so what I did is: while checking condition if fields are common in both Input_files then re-create the line with new last value and then by mentioning 1 printing the current(edited/non-edited) lines.

Related