Find and replace words in files

I have two files: file1 and file2.

Any match in file2 should append "-W" to the word in file1.

File1:

Verb=Applaud,Beg,Deliver
Adjective=Bitter,Salty,Minty
Adverb=Quickly,Truthfully,Firmly

file2:

Gate
Salty
Explain
Quickly
Hook
Deliver
Earn
Jones
Applaud
Take

Conclusion:

Verb=Applaud-W,Beg,Deliver-W
Adjective=Bitter,Salty-W,Minty
Adverb=Quickly-W,Truthfully,Firmly

I tried, but did not work and may take too much time:

for i in `cat file2` ; do
nawk -v DEE="$i" '{gsub(DEE, DEE"-W")}1' file1 > newfile
mv newfile file1
done
+4
source share
4 answers

This should work:

sed 's=^=s/\\b=;s=$=\\b/\&-W/g=' file2 | sed -f- file1

Conclusion:

Verb=Applaud-W,Beg,Deliver-W
Adjective=Bitter,Salty-W,Minty
Adverb=Quickly-W,Truthfully,Firmly

To make changes:

sed 's=^=s/\\b=;s=$=\\b/\&-W/g=' file2 | sed --in-place -f- file1
+2
source

Your approach was not so bad, but I would prefer it sedhere, since it has an option in place.

while read i
do
    sed -i "s/$i/$i-W/g" file1
done < file2
+1
source

This uses pure bash:

#!/bin/bash
while read line
do
    while read word
    do
        if [[ $line =~ $word ]]; then
            line="${line//$word/$word-W}"
        fi
    done < file2
    echo $line
done < file1
0
source

An awk:

awk 'BEGIN{FS=OFS=",";RS="=|\n"}
     NR==FNR{a[$1]++;next}
     {
        for (i=1;i<=NF;i++){
            $i=($i in a) ? $i"-W":$i
            }
        printf("%s%s",$0,FNR%2?"=":"\n")
    }'  file2 file1

results

Verb=Applaud-W,Beg,Deliver-W
Adjective=Bitter,Salty-W,Minty
Adverb=Quickly-W,Truthfully,Firmly
0
source

All Articles