1

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
1
  • 1
    Hello, welcome on SO. What you wrote does not make much sense. When looking at similar Q&A you should really try to understand. Random copy-paste works only in exceptional circumstances. Your awk script is syntactically incorrect (not mentioning that if you don't record the mapped values you obviously cannot use them for replacement). And you are using file names with spaces in your example; as you wrote it this cannot work. Commented Jul 29, 2021 at 12:53

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Aaand mapping.sed can be generated from the presented mapping file with just sed 's@\(.*\) \(.*\)@s/\1/\2/g@' mapping_file > mapping.sed.
What if names in the .sed file needs to have /
@Aragon use | as delimiter, e.g. to replace slash characters using slash word you might write s|/|slash|g
2

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
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.