Home > Software design >  Prepending letter to field value
Prepending letter to field value

Time:10-22

I have a file 0.txt containing the following value fields contents in parentheses:

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

I'm looking in OS and elsewhere for how to prepend the letter x to the beginning of each value between commas so that my output file becomes (using bash unix):

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

the only thing I've really tried but not enough is:

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

for all purposes the prefix should not be applied to the last commas at the end of each line.

CodePudding user response:

With awk

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

CodePudding user response:

The trick is to anchor the regexp so that it matches the whole comma-terminated substring you want to work with, not just the comma (and avoids other “special” characters in the syntax).

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