bash - 使用该行

时间:2018-02-15 13:15:15

标签: bash awk sed

我有一个输入文件:

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'

但这只会取代第一次出现。

有什么建议吗?

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

关注$("#".id).attr("disabled","disabled");可能对您有帮助。

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.

答案 2 :(得分:1)

使用sed

sed -E '
:A
s/([^=]*)(=[^,]*),([^,]*)/\1\2\1\/\3 /
tA
s/.*=//
' infile