字段值前加字母



我有一个文件0.txt,包含以下括号中的值字段内容:

(bread,milk,),
(rice,brand B,),
(pan,eggs,Brandc,),

我正在OS和其他地方寻找如何将字母x添加到逗号之间的每个值的开头,以便我的输出文件变成(使用bash unix):

(xbread,xmilk,),
(xrice,xbrand B,),
(xpan,xeggs,xBrand C,),

我唯一真正尝试过但还不够的是:

awk '{gsub(/,/,",x");print}' 0.txt

无论如何,前缀不应应用于每行末尾的最后一个逗号。

Withawk

awk 'BEGIN{FS=OFS=","}{$1="(x"substr($1,2);for(i=2;i<=NF-2;i++){$i="x"$i}}1'

解释:

# Before you start, set the input and output delimiter
BEGIN{
FS=OFS=","
}
# The first field is special, the x has to be inserted
# after the opening (
$1="(x"substr($1,2)

# Prepend 'x' from field 2 until the previous to last field
for(i=2;i<=NF-2;i++){
$i="x"$i
}
# 1 is always true. awk will print in that case
1 

诀窍是锚定regexp,以便它匹配您想要处理的整个以逗号结尾的子字符串,而不仅仅是逗号(并避免语法中的其他"特殊"字符)。

awk '{ gsub(/[^,()]+,/, "x&") } 1' 0.txt
sed -r 's/([^,()]+,)/x1/g' 0.txt

最新更新