[英]Replace a specific pattern with SED
我需要有關如何編寫SED襯紙(無awk)的幫助,該襯紙用相同長度的模式替換一行的子字符串。 例如,如果文件如下所示:
daemon www X=1 ***Y=1,2,2*** Z= daemon www X=1 ***Y=1,2,2,1,3,4,5*** Z=4 daemon mail a=3
我想只更改包含“守護程序www”的行和子串Y = ..使用相同數量的零。 ( #,#,#,#
數量未知)。
輸出文件應如下所示:
daemon www X=1 ***Y=0,0,0*** Z=4 daemon www X=1 ***Y=0,0,0,0,0,0,0*** Z=4 daemon mail a=3
有任何想法嗎 ? 謝謝 !
單程:
sed '/daemon www.*Y=/{:l s/\(Y=\(0,\)*\)[0-9]*/\10/;/Y=\(0,\)*0\([^,0-9]\|$\)/!bl}' input
一些解釋:
if this line contains daemon www and Y= # /daemon www.*Y=/{
loop # :l
a. find Y= and zeros followed by commas # s/\(Y=\(0,\)*\)
b. find a series of digits # [0-9]*
c. replace matches in 'a' and 'b' with # /\10/g
'a' and 0
d. jump to loop if cannot match the
desired pattern: Y=0,0..,0 # /Y=\(0,\)*0
e. and the pattern in d ends with a
non-digit non-comma character or the
end of line # \([^,0-9]\|$\)/!bl
嘗試:
sed '/^daemon www.*Y/{s/[0-9]\([,*]\)/0\1/g}'
實際上:
$ cat input
daemon www X=1 ***Y=1,2,2*** Z=
daemon www X=1 ***Y=1,2,2,1,3,4,5*** Z=4
daemon mail a=3
$ sed '/^daemon www.*Y/{s/[0-9]\([,*]\)/0\1/g}' input
daemon www X=1 ***Y=0,0,0*** Z=
daemon www X=1 ***Y=0,0,0,0,0,0,0*** Z=4
daemon mail a=3
我會用awk
。 但是,如果您真的必須使用sed
,則可以忽略它。
awk '/daemon www.*Y=*/{for(i=1;i<=NF;i++) ($i~/Y=/)?gsub(/[0-9]/,"0",$i):$i}1' file
$ cat file
daemon www X=1 ***Y=1,2,2*** Z=
daemon www X=1 ***Y=1,2,2,1,3,4,5*** Z=4
daemon mail a=3 Y=3,45,
$ awk '/daemon www.*Y=*/{for(i=1;i<=NF;i++) ($i~/Y=/)?gsub(/[0-9]/,"0",$i):$i}1' file
daemon www X=1 ***Y=0,0,0*** Z=
daemon www X=1 ***Y=0,0,0,0,0,0,0*** Z=4
daemon mail a=3 Y=3,45,
嘗試這個:
sed -e 's/^\(daemon www X=1 .*Y=\)[0-9]\+/\10/' -e 's/,[0-9]\+/,0/g'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.