Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepending letter to field value

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.

like image 298
7beggars_nnnnm Avatar asked Jan 23 '26 06:01

7beggars_nnnnm


2 Answers

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 
like image 87
hek2mgl Avatar answered Jan 25 '26 22:01

hek2mgl


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
like image 38
Andrej Podzimek Avatar answered Jan 25 '26 21:01

Andrej Podzimek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!