mike
mike

Reputation: 49

replace string from a file based on a mapping file

i want to replace multiple instances of strings with those from mapping file.

Mapping file

T0169 atr
T0175 klm
T0180 gtu
T0186 nik
T0201 nit

Working file-1

SN_abc.txt
T0169
SN_def.txt
T0175
T0201
SN_ghi.txt
T0169
T0180
T0175
SN_jkl.txt
T0180
T0201
T0175

output

SN_abc.txt
atr
SN_def.txt
klm
nit
SN_ghi.txt
atr
nik
klm
SN_jkl.txt
gtu
nit
klm

Things i tried by looking at similiar posts, but did not work

awk 'NR==FNR {a[$1]++; next} $1 in a' mapping file working file-1 > output.txt


join -1 1 -2 1 -a 1 -o 0,2.2 mapping file working file-1 > output.txt

Upvotes: 1

Views: 1134

Answers (2)

Daweo
Daweo

Reputation: 36500

You might harness GNU sed's -f for this task, first rework your mapping file into file understood by sed, say mapping.sed with content as follows

# sed replacements 
s/T0169/atr/g
s/T0175/klm/g
s/T0180/gtu/g
s/T0186/nik/g
s/T0201/nit/g

then use it as follows

sed -f mapping.sed <workingfile.txt >output.txt

Upvotes: 2

James Brown
James Brown

Reputation: 37404

In awk:

$ awk '
NR==FNR {                       # process first file
    a[$1]=$2                    # hash to a, key is the value to replace in file2
    next                        # on to next record
}
{                               # process second file
    print (($1 in a)?a[$1]:$1)  # output value hashed if found - or value
}' file1 file2                  # mind th order

Head of output:

SN_abc.txt
atr
SN_def.txt
klm
nit
...

Upvotes: 2

Related Questions