codenameyau/sed-awk-cheatsheet

Sed skills: Commatize any number

codenameyau opened this issue · 1 comments

Write a sed script that will commatize any digit number.

Input

1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000000
100000000000
1000000000000

Output

1
10
100
1,000
10,000
100,000
1,000,000
10,000,000
100,000,000
1,000,000,000
10,000,000,000
100,000,000,000
1,000,000,000,000
# Example on the internets.
sed ':a;s/\B[0-9]\{3\}\>/,&/;ta' text/numbers.txt

# Clearer syntax for above.
sed -r ':loop; s/\B[0-9]{3}\>/,&/; t loop' text/numbers.txt

# With loop and most readable.
sed -r ':loop; s/(.*[0-9])([0-9]{3})/\1,\2/; t loop' text/numbers.txt