簡體   English   中英

使用sed查找並替換模式的所有實例

[英]Use sed to find and replace all instances of a pattern

我對sed不太滿意。 看起來很復雜。 但是我很想學習如何用另一個字符串替換一個字符串的所有實例

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

但是,如果我想說所有以“ a”開頭並有第三個字母“ p”的單詞替換為水果,我該怎么做?

這可能對您有用(GNU sed):

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

這使用了\\<開口字邊界作為一個字的一個字符開始的開始標記a ,隨后另一字字符,接着是p ,隨后的零個或多個單詞字符,接着是\\>閉合字全局將被“ fruit ”一詞代替。

鑒於:

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

你可以做:

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

如果您只想要單詞(而不是該行的其余部分),則可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM