Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to sum floats which use the comma as separator, and gawk does integer calculations. Here's the script:

BEGIN {
  FS=";"
  OFS=";"
  CONVFMT = "%2.2f"
}
{ 
  print $1
  print $2
  print $1+$2 
}

I'm using this data file:

4,3;5,7

and calling the script like this:

LC_ALL=fr_BE gawk -f test.awk < t.txt

I get this output:

4,3
5,7
9

I have the fr_BE locale set up, but the result is still incorrect. How can I fix this?

share|improve this question

2 Answers 2

The answer is to use the --use-lc-numeric gawk option.

--use-lc-numeric

This forces gawk to use the locale's decimal point character when parsing input data. Although the POSIX standard requires this behavior, and gawk does so when --posix is in effect, the default is to follow traditional behavior and use a period as the decimal point, even in locales where the period is not the decimal point character. This option overrides the default behavior, without the full draconian strictness of the --posix option.

Example

Say we have this data file:

$ cat t.txt 
4,3;5,7
4,9;5,7

To ease in seeing the output, I changed this line in test.awk:

print "Total: "$1+$2 

Now when you run it using the above mentioned switch:

$ LC_ALL=fr_BE gawk --use-lc-numeric -f test.awk < t.txt
4,3
5,7
Total: 10
4,9
5,7
Total: 10,60

References

share|improve this answer
    
I think this solution will not work. gawk can not convert string 4,3 to float number. –  cuonglm Mar 23 at 13:06
    
@Gnouc do you think or know it? I tried it with gawk 3 an 4 and it seems to work.. –  Scrutinizer Mar 23 at 16:34
    
I try with gawk 3.1.8, Ubuntu 12.04 and it does not work. –  cuonglm Mar 23 at 16:40

I think the problem is gawk can not convert string 4,3 to a float number. You can fix it by replace , with .. For @glenn jackman input:

BEGIN {
  FS=";"
  OFS=";"
  CONVFMT = "%2.2f"
}
{
  gsub(",",".",$0)
  print $1
  print $2
  print $1+$2
}

$ LC_ALL=fr_BE gawk -f test.awk < file
4.3
5.7
10
4.9
5.7
10.6
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.