Reputation: 393
cat file1
xizaoshuijiao @E0488_5@
chifandaqiu @E0488_3@
gongzuoyouxi @E0977_5@
cat file2
@E0488_3@ @E0488_3@
@E0488_5@ @E0488_5@
@E0977_3@ @E0977_3@
@E0977_5@ @E0977_5@
@E0977_6@ @E0977_6@
Purpose:if $NF in file1 found in file2 $1, than replace $NF in file1 with file2 $2.otherwise, makes no change.
My code:
awk '\
NR==FNR{a[$1]=$1;b[$2]=$2;next}\
{if($NF in a)\
{$NF=b[FNR];print $0}\
else if!($NF in a)\
{print $0}\
}' file2 file1
Then it came error:
awk: cmd. line:5: else if!($NF in a)\
awk: cmd. line:5: ^ syntax error
awk: cmd. line:6: {print $0}\
awk: cmd. line:6: ^ syntax error
So it seems that "!" issue. because I want to print all content in file1(both changed line and unchanged line).How can I do it ?
Upvotes: 1
Views: 983
Reputation: 113844
Replace:
if!($NF in a)
With:
if(!($NF in a))
!
is part of the test-condition and awk expects the test-condition to all be inside parens.
Upvotes: 2
Reputation: 67497
you can rewrite it in this form
awk 'NR==FNR {a[$1]=$2; next}
$NF in a {$2=a[$1]}1' file2 file1
since your file2 has the same values for $1 and $2, it seems useless.
Since you want to print unconditionally, don't print in the condition block. Here 1
corresponds to {print}
which is the same as {print $0}
Upvotes: 3
Reputation: 393
Here comes my code after verification.
awk '\
NR==FNR{a[$1]=$1;b[$2]=$2;next}\
{if($NF in a)\
{$NF=b[FNR];print $0}\
else # use else... it will work, no need else if... , but why ? How can I achieve it with else if !($NF in a)
{print $0}\
}' file2 file1
Upvotes: 0