-1

I have 2 files. The first column (separated by ",") in file1.txt is equal in file2.txt. I want to compare both files and replace for second column in the file1.txt in file2.txt

file1.txt

ABC-aBc-AbC,abc-abc-abc
AAA-AAA-AAA,aaa-aaa-aaa

file2.txt

text text ABC-aBc-AbC text text text AAA-AAA-AAA text text.
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

1

I assume what you mean is that file2.txt is a free-form text file that may contain instances of the first-column strings from file1.txt, and you want to replace them by the corresponding second-column strings.

If file1.txt doen't contain any regular expression special characters, then one fairly efficient way to do that might be to turn it into a sed script, and then apply the sed script to the second file i.e.

sed 's/.*/s,&,g/' file1.txt | sed -f- file2.txt
text text abc-abc-abc text text text aaa-aaa-aaa text text.

Alternatively, (and this time assuming that the strings in file2.txt are whitespace separated) you could build a lookup table from the entries in file1.txt and then loop over the fields of file2.txt and make the corresponding substitutions:

awk -F, 'NR==FNR {a[$1]=$2; next} {for (i=1;i<=NF;i++) {if ($i in a) $i = a[$i]}} 1' file1.txt FS='[ \t]+' file2.txt
text text abc-abc-abc text text text aaa-aaa-aaa text text.

or

awk -F, 'NR==FNR {a[$1]=$2; next} {for (i=1;i<=NF;i++) {$i = $i in a? a[$i] : $i}} 1' file1.txt FS='[ \t]+' file2.txt
text text abc-abc-abc text text text aaa-aaa-aaa text text.
steeldriver
  • 81,074