bash-使用从该行捕获的模式替换该行中的所有引用

bash-使用从该行捕获的模式替换该行中的所有引用,bash,awk,sed,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' 但这只会取代第一次 有什么建议吗?关于awk: 或使用gs

我有一个输入文件:

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:

或使用gsub/sub替换的较短版本:

awk -F'=' '{ gsub(",", OFS $1"/"); sub(/^[^ ]+ /, "") }1' file
使用awk:

或使用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
以下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 -E '
:A
s/([^=]*)(=[^,]*),([^,]*)/\1\2\1\/\3 /
tA
s/.*=//
' infile
与塞德

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

sed在这方面不是很好,因为/g将导致在上一次匹配后恢复搜索,而不是重新处理整行。您可以使用循环解决此问题,但我会使用Awk来解决此问题。预期输出中的第一个空格是可选的还是必需的?空格是可选的对于这一点不是很好,因为/g将导致搜索在上一次匹配后恢复,而不是重新处理整行。你可以通过循环来解决这个问题,但我会选择Awk。预期输出中的第一个空格是可选的还是必需的?空格是可选的。你能解释一下这一部分吗?ORS:OFS?@Mago,如果我们到达最后一个字段i==NF?->打印ORS换行符,否则->打印其他字段的S空格。因此,在遇到最后一个时添加记录分隔符field@RomanPerekhrest,我的解决方案离你更近了一点,免责声明:没有复制,我相信有点不同:很好。你能解释一下这一部分吗?ORS:OFS?@Mago,如果我们到达最后一个字段i==NF?->打印ORS换行符,否则->打印其他字段的S空格。因此,在遇到最后一个时添加记录分隔符field@RomanPerekhrest,我的解决方案与您更接近,免责声明:没有复制,我相信没有什么不同: