7

Can anyone tell me how to use the awk command for this statement "the number will contain commas after every three digits. For example, 100000000 will become 100,000,000."

I know how to use sed command to obtain this output but I don't know how to use awk, I'm beginner please tell me I'm searching from morning but I didn't get a suitable answer for this so please suggest me best tutorials for learning.

sed command to get the above output:

echo "100000000" | sed -E 's/([0-9]{3})/,\1/2g'
  • 1
    What search term are you using? Try "thousands separator". FYI GNU awk has a printf format modifier – steeldriver Dec 13 '15 at 18:22
  • 2
    Your sed command doesn't do what you think. It only works with 9-digit numbers... – don_crissti Dec 13 '15 at 18:28
  • search term stands for "to search on internet to resolve this" – Error3735 Dec 14 '15 at 18:27
  • Alright! i have seen it'll work just for 9 digit numbers and i want a same output for same numbers but by using the awk can you help me? – Error3735 Dec 14 '15 at 18:29
11

A locale-independent solution with manual formatting

This should work on any POSIX-compatible OS regardless of the locales installed.

$ printf "1\n10\n100\n1000\n10000\n100000\n1000000\n10000000\n100000000\n" \
| awk '{ len=length($0); res=""; for (i=0;i<=len;i++) { res=substr($0,len-i+1,1) res; if (i > 0 && i < len && i % 3 == 0) { res = "," res } }; print res }'
1
10
100
1,000
10,000
100,000
1,000,000
10,000,000
100,000,000

A solution that uses printf and the en_US locale.

The printf sequence %'d prints a decimal integer formatted with the current locale's thousands separator.

$ printf "1\n10\n100\n1000\n10000\n100000\n1000000\n10000000\n100000000\n" \
| LC_ALL=en_US.UTF-8 awk '{ printf("%'"'"'d\n", $0) }'
1
10
100
1,000
10,000
100,000
1,000,000
10,000,000
100,000,000

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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