user3437245
user3437245

Reputation: 347

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

Output:

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

Tried but not working and may take too long:

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

Upvotes: 4

Views: 105

Answers (4)

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14945

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

Upvotes: 0

Jahid
Jahid

Reputation: 22428

This should work:

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

Output:

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

To make changes in place:

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

Upvotes: 2

Nathan Wilson
Nathan Wilson

Reputation: 856

Here is one using 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

Upvotes: 0

Rambo Ramon
Rambo Ramon

Reputation: 1034

Your approach was not that bad but I would prefer sed here, since it has an in place option.

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

Upvotes: 1

Related Questions