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
3

2 Answers 2

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.

2
  • 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? Commented Dec 6, 2016 at 7: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. Commented Dec 6, 2016 at 13:07
1
#!/bin/bash

IFS=";"
while read NAME VALUE
do
    sed -i "s/${NAME}/${VALUE}/g" file1
done < file2
1
  • This would also replace the words when they occur as substrings, as in LightBlue. Commented Apr 20, 2019 at 16:08

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.