1

I have these as input files

file1

Red + Yellow = Orange; Yellow + Blue = Green; Blue + Red = Violet

file2

Red;1
Yellow;2
Blue;3

I am doing this in unix.

Output

file3

1 + 2 = Orange; 2 + 3 = Green; 3 + 1 = Violet
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
peon
  • 23

2 Answers2

1
awk 'NR == FNR { # First file
    split($0,a,/;/)
    #print "change " a[1] "to " a[2]
    change[a[1]]=a[2]
}
NR != FNR {
    for (i=1;i<NF;i++) {
            if ($i in change) {
                    $i=change[$i]
            }
    }
    print
}' file2 file1

Use the awk idiom NR != FNR to tell if this is the first file or the second. If it is the first file then split the line on ; and store the mapping in the change array. If it is the second then loop over the input field, if any match then replace with the correct change. At the end print the result.

icarus
  • 17,920
  • Thank you for that. What if I change my file 2 into something like this? Red;1 2 Yellow;2 3 Blue;3 1

    And the output file will look like this 1 2 + 2 3 = Orange; 2 3 + 3 1 = Green; 3 1 + 1 2 = Violet

    which is essentially just replacing the strings in file1 with the corresponding string in the 2nd col of file2. Will this still work?

    – peon Dec 06 '16 at 07:17
  • @peon please edit your question to show the data files, and try the commands. If I understand your comment correctly the answer is yes. – icarus Dec 06 '16 at 13:07
1
#!/bin/bash

IFS=";"
while read NAME VALUE
do
    sed -i "s/${NAME}/${VALUE}/g" file1
done < file2
Kamaraj
  • 4,365