This is driving me nuts, can't think of any easy way to do it.
I need to append a string ".00" only in the third field of a file, and only if it does NOT have a decimal point already
Here is what the file looks like-
1400030846,2,17,POL GENERAL
1400030900,3,14.95,FIC GENERAL
If you look, the first line has no .00 after the 17 and I need all the price fields to have a decimal in them, so if it has none, I need to append .00 to it.
The second line is fine as it contains a decimal.
If you are curious these are inventory files, the fields are- isbn, quantity, price, store section
---------- Post updated at 01:22 PM ---------- Previous update was at 01:15 PM ----------
I always read the "awk" posts carefully because I'm trying to become a superawker. I'm having trouble figuring out what the number 1 does in your example. I fooled around with it and it doesn't seem to matter what number is there. Just that one is:
$ awk -F, '{$3=sprintf("%.2f",$3)}1' OFS="," testfile
1400030846,2,17.00,POL GENERAL
1400030900,3,14.95,FIC GENERAL
$ awk -F, '{$3=sprintf("%.2f",$3)}' OFS="," testfile
$ awk -F, '{$3=sprintf("%.2f",$3)}1' OFS="," testfile
1400030846,2,17.00,POL GENERAL
1400030900,3,14.95,FIC GENERAL
$ awk -F, '{$3=sprintf("%.2f",$3)}2' OFS="," testfile
1400030846,2,17.00,POL GENERAL
1400030900,3,14.95,FIC GENERAL
$ awk -F, '{$3=sprintf("%.2f",$3)}3' OFS="," testfile
1400030846,2,17.00,POL GENERAL
1400030900,3,14.95,FIC GENERAL
$ awk -F, '{$3=sprintf("%.2f",$3)}4' OFS="," testfile
1400030846,2,17.00,POL GENERAL
1400030900,3,14.95,FIC GENERAL
$ awk -F, '{$3=sprintf("%.2f",$3)}23123412341234' OFS="," testfile
1400030846,2,17.00,POL GENERAL
1400030900,3,14.95,FIC GENERAL
$ awk -F, '{$3=sprintf("%.2f",$3)}23123412341234.2345' OFS="," testfile
1400030846,2,17.00,POL GENERAL
1400030900,3,14.95,FIC GENERAL
If you don't mind, I'd appreciate if you (or anyone who knows) could take a second and explain why that is.
awk evaluates the 1 or any value other then 0 (even a variable with a value that's != 0 or != "") after the brace as true and the prints the current line by default, equivalent to {print}.
while(<DATA>){
s/,([0-9]+),(?=[A-Za-z]+)/",".$1.".00,"/e;
print;
}
__DATA__
1400030846,2,17,POL GENERAL
1400030900,3,14.95,FIC GENERAL
1400030900,3,14.05,FIC GENERAL
1400030900,3,14,FIC GENERAL