簡體   English   中英

在多行中搜索和替換模式

[英]Search and replace patterns on multiple line

我有一個像

Fixed pattern
text which can change(world)

我想用替換

Fixed pattern
text which can change(hello world)

我正在嘗試使用的

cat myfile | sed -e "s#\(Fixed Pattern$A_Z_a_z*\(\)#\1 hello#g > newfile

更新:上面的單詞世界也是一個變量,將發生變化基本上在表達式后的第一個括號之后添加問候。

提前致謝。

假設您的目標是在'Fixed pattern'之后的行中每個圓括號內添加'hello ' ,那么以下解決方案應該可以使用:

sed -e '/^Fixed pattern$/!b' -e 'n' -e 's/(/(hello /' myfile

這是每個部分的說明:

/^Fixed pattern$/!b    # skip all of the following commands if 'Fixed pattern'
                       #   doesn't match
n                      # if 'Fixed pattern' did match, read the next line
s/(/(hello /           # replace '(' with '(hello '

為此,請使用n

sed '/Fixed pattern/{n; s/world/hello world/}' myfile

您可能需要更加小心,但這在大多數情況下都應該起作用。 只要sed看到Fixed pattern (您可能要使用行錨^$ ),它將讀取下一行,然后對其應用替換。

暫無
暫無

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

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