fabioln79
fabioln79

Reputation: 395

find and replace with sed

I have the following problem.

I have a file with a lot of words inside what I have to do is find these words in another file and replace them with just one letter.

I do not know the words that I have to delete (too many!) so I don't know how to use the following sed command

$ sed -i 's/words_old/word_new/g' /home/user/test.txt

however I think I have to use also the cat command:

$ cat filewithwordstobedeleted.txt

but I don't know how to combine them.

Thank you for helping me! :)

Fabio

Upvotes: 3

Views: 1083

Answers (3)

potong
potong

Reputation: 58351

This might work for you (GNU sed):

# cat <<\! >/tmp/a
> this
> that
> those
> !
cat <<\! >/tmp/b
> a
> those
> b
> this
> c
> that
> d
> !
sed 's|.*|s/&/null/g|' /tmp/a
s/this/null/g
s/that/null/g
s/those/null/g
sed 's|.*|s/&/null/g|' /tmp/a | sed -f - /tmp/b
a
null
b
null
c
null
d
cat <<\! >/tmp/c
> a
> this and that and those
> b
> this and that
> c
> those
> !
sed 's|.*|s/&/null/g|' /tmp/a | sed -f - /tmp/c
a
null and null and null
b
null and null
c
null

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 359855

If your list of words is one-per-line and not ridiculously long:

sed -ri "s/$(tr "\n" "|" < filewithwordstobedeleted.txt | head -c-1)/null/g" /home/user/test.txt

Upvotes: 0

thiton
thiton

Reputation: 36049

A simple shell loop could help you here, assuming you have one word-to-be-deleted per line:

cat filewithwordstobedeleted.txt | while read word; do
    sed -i "s/$word/null/g" /home/user/test.txt
done

Note that the use of cat is not strictly necessary, but makes this example easier to read.

Upvotes: 3

Related Questions