[英]Sed-Replace immediate next string word coming after a particular pattern but only the first occurrence in a file
我需要一個sed
命令,該命令將在模式之后立即替換字符串,但僅在文件中首次出現時替換
為了替換第一次出現,給出了:
sed -i '' -e '0,/abc/s//def/' filename
這將替換匹配的字符串,而不是匹配后的字符串
對於匹配后立即替換字符串,給出了:
sed -i 's/\(text=\)\(.*\)/\1qwerty/' filename
這將在匹配后立即替換字符串,但是將對所有匹配項都起作用。
在文件中,字符串兩次“ text = abc”是這樣的:
abc
text=occurrence1
qwe
uio
text=occurrence2
dsf
我想用字符串“ qwerty”替換occurence1
部分,以便輸出看起來像:
text=qwerty.
但是我只想在文件中第一次出現而不是在所有地方都這樣做。
使用GNU sed
應該可以:
例:
cat file:
abc
text=xyz1
qwe
uio
text=xyz
dsf
現在,僅將字符串“ text =“的第一次出現替換為” text = qwerty”:
sed -r '0,/text=/{s/text=(.*)/text=qwerty/}' file
輸出:
abc
text=qwerty
qwe
uio
text=xyz
dsf
sed
選項“ -r”:
-r : --regexp-extended, to use extended regular expressions
嘗試這個:
r="qwerty"
sed -i '' -e "1,/text=/s/\(text=\).*/\1${r}/" filename
這很簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.