sed whole word search and replace

2019-01-03 08:27发布

How do I search and replace whole words using sed?

Doing

sed -i 's/[oldtext]/[newtext]/g' <file> 

will also replace partial matches of [oldtext] which I don't want it to do.

标签: shell sed
6条回答
对你真心纯属浪费
2楼-- · 2019-01-03 09:03

In one of my machine, delimiting the word with "\b" (without the quotes) did not work. The solution was to use "\<" for starting delimiter and "\>" for ending delimiter.

To explain with Joakim Lundberg's example:

$ echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
no bar embarassment
查看更多
不美不萌又怎样
3楼-- · 2019-01-03 09:04

\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):

$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment
查看更多
倾城 Initia
4楼-- · 2019-01-03 09:10

in shell command:

echo "bar embarassment" | sed "s/\bbar\b/no bar/g" 

or:

echo "bar embarassment" | sed "s/\<bar\>/no bar/g"

but if you are in vim, you can only use the later:

:% s/\<old\>/new/g
查看更多
Explosion°爆炸
5楼-- · 2019-01-03 09:11

On Mac OS X, neither of these regex syntaxes work inside sed for matching whole words

  • \bmyWord\b
  • \<myWord\>

Hear me now and believe me later, this ugly syntax is what you need to use:

  • /[[:<:]]myWord[[:>:]]/

So, for example, to replace mint with minty for whole words only:

  • sed "s/[[:<:]]mint[[:>:]]/minty/g"

Source: re_format man page

查看更多
▲ chillily
6楼-- · 2019-01-03 09:25

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>
查看更多
一纸荒年 Trace。
7楼-- · 2019-01-03 09:28
$ echo "bar embarassment"|awk '{for(o=1;o<=NF;o++)if($o=="bar")$o="no bar"}1'
no bar embarassment
查看更多
登录 后发表回答