Obada abu alhiga
Obada abu alhiga

Reputation: 3

AWK with If condition

i am trying to replace the following string for ex: from

['55',2,1,10,30,23],  

to

['55',2,555,10,30,23],

OR

['55',2,1,10,30,23], 

to

['55',2,1,10,9999,23],

i search around and find this :

$ echo "[55,2,1,10,30,23]," | awk -F',' 'BEGIN{OFS=","}{if($1=="[55"){$2=10}{print}}'    

[55,10,1,10,30,23],

but it's not working in my case since there is " ' " around the value of $1 in my if condition :

$ echo "['55',2,1,10,30,23]," | awk -F',' 'BEGIN{OFS=","}{if($1=="['55'"){$2=10}{print}}'

['55',2,1,10,30,23],

Upvotes: 0

Views: 178

Answers (2)

Wintermute
Wintermute

Reputation: 44023

The problem is not in the awk code, it's the shell expansion. You cannot have single quotes in a singly-quoted shell string. This is the same problem you run into when you try to put the input string into single quotes:

$ echo '['55',2,1,10,30,23],'
[55,2,1,10,30,23],

-- the single quotes are gone! And this makes sense, because they did their job of quoting the [ and the ,2,1,10,30,23], (the 55 is unquoted here), but it is not what we wanted.

A solution is to quote the sections between them individually and squeeze them in manually:

$ echo '['\''55'\'',2,1,10,30,23],'
['55',2,1,10,30,23],

Or, in this particular case, where nothing nefarious is between where the single quotes should be,

echo '['\'55\'',2,1,10,30,23],'   # the 55 is now unquoted.

Applied to your awk code, that looks like this:

$ echo "['55',2,1,10,30,23]," | awk -F',' 'BEGIN{OFS=","}{if($1=="['\'55\''"){$2=10}{print}}'
['55',10,1,10,30,23],

Alternatively, since this doesn't look very nice if you have many single quotes in your code, you can write the awk code into a file, say foo.awk, and use

echo "['55',2,1,10,30,23]," | awk -F, -f foo.awk

Then you don't have to worry about shell quoting mishaps in the awk code because the awk code is not subject to shell expansion anymore.

Upvotes: 1

Kent
Kent

Reputation: 195029

I think how to match and replace is not the problem for you. The problem you were facing is, how to match a single quote ' in field.

To avoid to escape each ' in your codes, and to make your codes more readable, you can assigen the quote to a variable, and use the variable in your codes, for example like this:

echo "['55' 1
['56' 1"|awk -v q="'" '$1=="["q"55"q{$2++}7'
['55' 2
['56' 1

In the above example, only in line with ['55', the 2nd field got incremented.

Upvotes: 0

Related Questions