Chris
Chris

Reputation: 62

Shell Scripting: Delete all instances of an exact word from file (Not pattern)

I'm trying to delete every instance of a certain word in a file. I can't make it so that it doesn't delete the pattern from other words. For example if I want to remove the word 'the' from the file. It will remove 'the' from 'then' and leave me with just 'n'.

Right now I have tried:

sed s/"$word"//g -i final_in 

And:

sed 's/\<"$word"\>//g' -i final_in

But neither of them have worked. I thought this would be pretty easy to Google, but every solution I find does not work properly.

Upvotes: 0

Views: 253

Answers (2)

Ali ISSA
Ali ISSA

Reputation: 408

# test
word='the'
echo 'aaa then bbb'  | sed -r "s/$word//g"

# To match exacte word, you can add spaces : 
word=then
echo 'aaa then bbb'  | sed -e "s/ $word / /g"


# to modify a file
word='the'
cat file.txt  | sed -r "s/ $word / /g" > tmp.txt
mv tmp.txt file.txt


# to consider ponctuations :
word=then
echo 'aaa. then, bbb'  | sed -e "s/\([:.,;/]\)* *$word *\([:.,;/]\)*/\1 \2/g"

Upvotes: 0

riteshtch
riteshtch

Reputation: 8769

$word='the'
$sed -r "s/\b$word\b//g" << HEREDOC
> Sample text
> therefore
> then
> the sky is blue
> HEREDOC
Sample text
therefore
then
 sky is blue

\b=word boundary

Upvotes: 1

Related Questions