How to replace a list of strings by another list
It would be easier to create a file with both the input and replacement strings on the same line (assuming that neither input nor replacement strings contain spaces). Then you can do so something simple like:
while read n k; do sed -i "s/$n/$k/g" file1; done < fileA
EDIT:
After seeing Nykakin's answer, I realized you can do the same thing with the two files you have combining his suggestion with mine:
paste fileA fileB | while read n k; do sed -i "s/$n/$k/g" file1; done
This is basically your first idea, but with the substitution commands put into a file, so they’re more manageable:
tmpfile=/tmp/Asasuser.$$ exec 3< fileA exec 4< fileB while read –r astring <&3 do read –r bstring <&4 echo "s/$astring/$bstring/" >> "$tmpfile" done exec 3<&- 4<&- sed –f "$tmpfile" file1 > out rm –f "$tmpfile"
This assumes that fileA
and fileB
have the same number of lines (and that that number is greater than zero) and that neither of them has any unescaped /
characters.
We can just generate command that we need. Let's say that files with lists are called lista and listb. Then we can use:
$ for i in $(paste lista listb -d/); do echo -n "-e 's/$i/g' "; done
to generate option for sed. Now we can use it with eval. Let's say our file is called test. We use:
$ eval "sed" $(for i in $(paste lista listb -d/); do echo -n "-e 's/$i/g' "; done) "test"