Reputation: 409
I am trying to replace text using sed at word boundaries. After looking at Beginning and end of words in sed and grep, I use:
echo "It is a @ at a@ ." | sed "s/\ba\b/#/g"
Output: It is # @ at a@ .
which works perfectly, but when I try to replace words which begin or end in special characters like @, it does not work.
echo "It is a @ at a@ ." | sed "s/\b@\b/#/g"
Output: It is a @ at a@ .
echo "It is a @ at a@ ." | sed "s/\ba@\b/#/g"
Output: It is a @ at a@ .
I am missing something ? How can I replace whole words that end in special characters using sed ?
Upvotes: 0
Views: 1623
Reputation: 174696
You need to use \B
$ echo "It is a @ at a@ ." | sed "s/\B@\B/#/g"
It is a # at a@ .
\b
- matches between a word char and non-word char (vice-versa)
\B
- matches between two word chars or two non-word chars.
So the char exists before @
is space which is a non-word character. So to match the boundary which exists between two non-word chars, you need to use \B
and the character exists after @
is also the space character. So here, you need to use \B
also.
For the second case, you have to use this,
$ echo "It is a @ at a@ ." | sed "s/\ba@\B/#/g"
It is a @ at # .
Upvotes: 2