Home > Net >  Lookup Value replacement in a text file
Lookup Value replacement in a text file

Time:11-11

I have a CSV File(File1) with Key,Value pair

Key1,Value1
Key2,Value2

I have a second file(File2) which is not a structured data where I have the Key data(Key1,Key2..etc). I will have to find the Key Data followed by constant (A) in below example and then the value to be replaced with.

File2 content before replacement

Dummy1  Key1 A Value-Old1 BB C
D2 D3  4   Key2 A Value-Old2 BB C

File2 content After replacement

Dummy1  Key1 A Value1 BB C
D2 D3  4   Key2 A Value2 BB C

Any inputs is highly appreciated achieving this through awk or sed

I followed this link to get some place, but my replacement file is an unstructured one as opposed to a CSV file as below https://unix.stackexchange.com/questions/126485/replacing-the-values-in-one-file-with-the-values-in-another-file-in-bash

CodePudding user response:

If you don't mind loosing some space characters in the output then you could use some awk:

awk -F ',' '
    NR == FNR { arr[$1] = $2; next }
    FNR == 1 { FS = " "; $0 = $0 }
    {
        for (i = 1; i <= NF-2; i  )
            if ($i in arr && $(i 1) == "A") {
                $(i 2) = arr[$i]
                break
            }
    }
    1
' file1.csv file2.txt
  • Related