[英]How to replace a pattern for all occurrences after a given line using Bash?
[英]bash - replace all occurrences in a line with a captured pattern from that line
我有一個輸入文件:
a=,1,2,3
b=,4,5,6,7
c=,8,9
d=,10,11,12
e=,13,14,15
我需要轉變成
a/1 a/2 a/3
b/4 b/5 b/6 b/7
c/8 c/9
d/10 d/11 d/12
e/13 e/14 e/15
因此,我需要捕獲=
號之前的詞組,並用\\1/
替換每個逗號。
我最成功的嘗試是:
sed 's@\([^,]*\)=\([^,]*\),@\2 \1/@g'
但這只會取代第一次出現的情況。
有什么建議么?
用awk
:
awk -F'[=,]' '{ for(i=3;i<=NF;i++) printf "%s/%s%s", $1,$i,(i==NF? ORS:OFS) }' file
輸出:
a/1 a/2 a/3
b/4 b/5 b/6 b/7
c/8 c/9
d/10 d/11 d/12
e/13 e/14 e/15
或更短的一個帶有gsub/sub
替換的:
awk -F'=' '{ gsub(",", OFS $1"/"); sub(/^[^ ]+ /, "") }1' file
跟隨awk
可能會幫助您。
awk -F"=" '{gsub(/\,/,FS $1"/");$1="";gsub(/^ +| +$/,"")} 1' Input_file
說明:現在也為上述解決方案添加了說明:
awk -F"=" '{
gsub(/\,/,FS $1"/"); ##Using global substitution and replacing comma with FS(field separator) $1 and a / for all occurrences of comma(,).
$1=""; ##Nullifying the first column now.
gsub(/^ +| +$/,"") ##Globally substituting initial space and space at last with NULL here.
}
1 ##awk works on method of condition then action, so by mentioning 1 making condition TRUE here and not mentioning any action so by default action is print of the current line.
' Input_file ##Mentioning the Input_file name here.
輸出如下:
a/1 a/2 a/3
b/4 b/5 b/6 b/7
c/8 c/9
d/10 d/11 d/12
e/13 e/14 e/15
與sed
sed -E '
:A
s/([^=]*)(=[^,]*),([^,]*)/\1\2\1\/\3 /
tA
s/.*=//
' infile
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.