Prepending letter to field value

74 Views Asked by At

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.

2

There are 2 best solutions below

0
hek2mgl On BEST ANSWER

With awk

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

Explanation:

# 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 
3
Andrej Podzimek On

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