I need to read every full word from each line of a file and replace every occurrence of that word (if found anywhere in the file) using sed
or awk
with the word from another file.
Contents of fileA.txt:
1, This is a Record One, Value1, Dummy_val1 One, $$MOON$$
2, This is a Record Two, Value2, Dummy_val2 Two, #LATER
3, This is a Record Three, Value3, Dummy_val3 Three, #LATER
4, This is a Record Four, Value4, Dummy_val4 Four, $$MOON$$
and then Search_Replace_File.txt gives the info about what word needs to be replaced with which:
One=Ten
Two=Twenty
Three=Thirty
Four=Forty
$$MOON$$=SUN
#LATER=SNOW
The expected output is as below.
1, This is a Record Ten, Value1, Dummy_val1 Ten, SUN
2, This is a Record Twenty, Value2, Dummy_val2 Twenty, SNOW
3, This is a Record Thirty, Value3, Dummy_val3 Thirty, SNOW
4, This is a Record Forty, Value4, Dummy_val4 Forty, SUN
Note:
- if an old word is replaced with a new word from the list and if there is a mapping of the new word to another word in the mapping file, it can still be replaced.
- Replacement strings might also include symbols like below etc. $$MOON$$=SUN #LATER=SNOW
Tried the below code so far but it doesn't replace words.
#!/bin/bash
while read var
do
search_string=`echo "$var"|awk -F= '{print $1}'`
replace_string=`echo "$var"|awk -F= '{print $2}'`
sed "s/$searchstring/$replacestring/g" fileA.csv > fileB.csv
done < Search_Replace_File.txt
mv fileB.csv fileA.csv
&
)? I assume you do not want to do partial word matches, only full word matches (e.g.Four
should not match the start of matchFourteen
), right? What characters are word-constituent for your purposes ([[:alnum:]_]
is the common set for word-constituent characters but YMMV)?if there is a mapping of the new word to another word in the mapping file, it can still be replaced
- I assume that means it's also OK if it's not replaced. Doing such recursive mappings leads to having to handle potentially infinite recursion (e.g. foo maps to bar but then bar maps to foo) so it gets ugly.