0

I want to delete words into a line. For example:

I want to delete one word in this line

And I want to delete 'one' to obtain:

I want to delete  word in this line

By passing the word through a variable. So far I have got:

WORD=one ; sed -n 's/"$WORD"//g' file.txt > newfile.txt

But, it doesn't do anything. Why not? And how can I make it work?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Another.Chemist
  • 2,386
  • 3
  • 29
  • 43
  • Variables aren't expanded inside single quotes, only inside double quotes. Double quotes inside single quotes don't have any special effect. – Barmar Apr 17 '14 at 03:26

1 Answers1

2
WORD=one ; sed -e "s/$WORD//g" file.txt > newfile.txt

the key moment is variable expansion. You have to be careful though because shell variable expansion may be sometimes not what you want. In hard cases you have to do something like this:

EXPANDVAR=one; NOEXPANDVAR=another; sed -e 's/'"$EXPANDVAR"'$NOEXPANDVAR//g' file.txt > newfile.txt

In this case sed will replace (remove) pattern one$NOEXPANDVAR , literally.

user3159253
  • 16,836
  • 3
  • 30
  • 56