ChrisJ
ChrisJ

Reputation: 35

How to ignore word delimiters in sed

So I have a bash script which is working perfectly except for one issue with sed.

full=$(echo $full | sed -e 's/\b'$first'\b/ /' -e 's/  / /g')

This would work great except there are instances where the variable $first is preceeded immediately by a period, not a blank space. In those instances, I do not want the variable removed.

Example:

full="apple.orange orange.banana apple.banana banana";first="banana"
full=$(echo $full | sed -e 's/\b'$first'\b/ /' -e 's/  / /g')
echo $first $full;

I want to only remove the whole word banana, and not make any change to orange.banana or apple.banana, so how can I get sed to ignore the dot as a delimiter?

Upvotes: 1

Views: 238

Answers (1)

glenn jackman
glenn jackman

Reputation: 246847

You want "banana" that is preceded by beginning-of-string or a space, and followed by a space or end-of-string

$ sed -r 's/(^|[[:blank:]])'"$first"'([[:blank:]]|$)/ /g' <<< "$full"
apple.orange orange.banana apple.banana 

Note the use of -r option (for bsd sed, use -E) that enables extended regular expressions -- allow us to omit a lot of backslashes.

Upvotes: 2

Related Questions