简体   繁体   中英

Use sed to find and replace all instances of a pattern

I'm not very good with sed. It just looks complicated. However I've mnaged to learn how to replace all instances of a string with another string

sed 's/replace-this/with-this/FLAG'

However, if I want to say replace all words that start with "a" and have a third letter "p", with fruit, how would I do that?

This might work for you (GNU sed):

sed 's/\<a\wp\w*\>/fruit/g' file

This uses the \\< opening word boundary as a marker for the start of a word beginning with a the character a , followed by another word character, followed by a p , followed by zero or more word characters, followed by a \\> closing word boundary to be replaced by the word fruit globally.

Given:

$ echo "$tgt"
app
apple
applesauce
grape
gum
apple is a fruit
text apple and pears

You can do:

$ echo "$tgt" | sed 's/a.p.*/fruit/'
fruit
fruit
fruit
grape
gum
fruit
text fruit

If you want the word only (not the remainder of the line) you can do:

$ echo "$tgt" | sed -E 's/a.p[a-zA-Z]*/fruit/'
fruit
fruit
fruit
grape
gum
fruit is a fruit
text fruit and pears

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM