I have a file 'book'(not txt) which contains text. I also have a list of words which I need to delete from said file. I have written this script but for some reason when I try to check and see if the file was changed after execution I get no changes. I tried outputing the result into book > output.txt but still 'output' has the same text as 'book'.

The code :

for word in {am pm cm words count ......}
    sed -i 's/${word}//g' book

do you have any idea why the words in the list aren't deleted as they should?


Variables are not expanded inside single quotes, but are expanded inside double quotes. You should go for

for word in am pm cm words count etc
  sed -i "s/${word}//g" book

Notice you could also call sed only one time and achieve the same with

sed -i "s/am\|pm\|cm\|words\|count//g" book

If the list of words are really long, you can use an array in bash and format it.

words=(am pm cm words count etc)

fmt=$(IFS='|'; printf '%q' "s/${words[*]}//g")

echo sed -i "$fmt" book
  • Just add more elements in the array words if need be.

  • Remove the echo so sed can do it's job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.