Issue
I have two files File 1
Create -l Ap -ne BP_v BP_v -cir {1 2 3 4}
Create -l Ap -ne BP_p BP_p -cir {1 2 3 4}
File 2
BP_v net1
BP_p net2
I want to search column 1 data of file1 in file2 and if found I want to replace that with column 2 data in file2.
output as
Create -l Ap -ne net1 net1 -cir {1 2 3 4}
Create -l Ap -ne net2 net2 -cir {1 2 3 4}
Anybody please help. I tried awk but not clear. I tried the code
awk 'NR==FNR{a[NR]=$1;b[NR]=$2;next}{$5=b[FNR];$6=b[FNR]}1' File 2 File 1
But its replacing line by line
Solution
You are replacing the values line by line because both files have 2 lines, and you use NR
and FNR
to index into the array, where NR
it the total record number and FNR
the record number in the current file.
You can build a key=value array a
reading file2, and then when reading file1, set field 5 and field 6 if that value occurs in the array a
awk 'FNR==NR{a[$1]=$2;next}
{
if ($5 in a) $5 = a[$5]
if ($6 in a) $6 = a[$6]
} 1' file2 file1
If the contents of file1 is:
Create -l Ap -ne BP_v BP_v -cir {1 2 3 4}
Create -l Ap -ne BP_p BP_p -cir {1 2 3 4}
Create -l Ap -ne BP_v BP_p -cir {1 2 3 4}
The output will be:
Create -l Ap -ne net1 net1 -cir {1 2 3 4}
Create -l Ap -ne net2 net2 -cir {1 2 3 4}
Create -l Ap -ne net1 net2 -cir {1 2 3 4}
Answered By - The fourth bird Answer Checked By - Marie Seifert (WPSolving Admin)