Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk stumper: regex substitution within a field

Tags:

regex

awk

I'm new to awk, and I can't seem to figure this one out. How can I substitute in a single field using a regular expression?

In perl, I could assign the field of interest to a variable, then $myvar =~ s/foo/bar/g. Of course also in perl I have to do my own field management, and that's easier in awk.

For the issue at hand just now, it's European money records and I want to change commas to periods in the amount field. But I need to target only that field, so I don't mangle the other fields where commas could be used as prose punctuation.

Is the solution more difficult than I imagine? Or simpler? Do I have to change the record separator or something tacky like that?

Thank you for your help!

like image 388
rockriver Avatar asked Feb 08 '11 08:02

rockriver


1 Answers

sub() accepts a third argument which is the field (or variable) to change:

$ echo '02/08/2011 7,33 Shopping' | awk '{sub(/,/,".",$2)} 1'
02/08/2011 7.33 Shopping
like image 134
marco Avatar answered Sep 27 '22 16:09

marco