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
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
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.
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:17yes
.
– icarus
Dec 06 '16 at 13:07
#!/bin/bash
IFS=";"
while read NAME VALUE
do
sed -i "s/${NAME}/${VALUE}/g" file1
done < file2
LightBlue
.
– Kusalananda
Apr 20 '19 at 16:08
strings
all single words, space delimited? – icarus Dec 06 '16 at 06:28