Hi , I have a file which contains text like
A|Mau|Code|12|Detail
B|Mau|Code|20|Header
I want to write a command using awk which will output
A|Mau|Code|12.00|Detail
B|Mau|Code|20.00|Header
I used a command like
awk -F"|" {printf "%s|%s|%s|%.2f|%s",$1,$2,$3,$4,$5}'
which does the job but could have been better.
any suggestions?
Perhaps
awk -F"|" -v OFS="|" '{ $4=sprintf("%.2f",$4); } 1'
1 Like
RudiC
3
Your approach needs two small corrections to print the desired output:
awk -F"|" '{printf "%s|%s|%s|%.2f|%s\n",$1,$2,$3,$4,$5}' file
A wee bit shorter would be
$ awk -F\| '$4+=1e-4' CONVFMT="%.2f" OFS="|" file
A|Mau|Code|12.00|Detail
B|Mau|Code|20.00|Header
(will fail on $4 == 0.0001, though)
Can you please explain what does "1" at the end does? I can see that i dont need to write print $0 to print the complete line
RudiC
5
awk
works on pattern {action}
pairs in a way that it evaluates the pattern, and, if TRUE, executes the action.
man awk
:
So - as 1
represents TRUE, awk
executes the default action print
.