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

closed as unclear what you're asking by G-Man, Jeff Schaller, Kiwy, Philippos, Stephen Kitt Feb 16 '18 at 15:10

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • I don't understand what you mean.You say that the first column is equal in each file but it doesn't appear that way. Are you trying to get the second file to look like AAA-AAA-AAA,abc-abc-abc? – Nasir Riley Feb 15 '18 at 20:02
  • do you want to do this on the command line using tools like sed and awk? (personally I would approach this with a python script) – fcbsd Feb 15 '18 at 20:28
  • 1
    Showing us sample input is only 25% of the job. You also need to show the corresponding output (another 25%) and provide a coherent description of the process (that’s 50%). And it would be nice if the data were human-readable, like real words instead of nonsense like ABC-aBc-AbC. – G-Man Feb 15 '18 at 22:58
  • Possible duplicate of How to perform replacements defined in one file on another file – Philippos Feb 16 '18 at 11:36
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.