1

I want to insert periods as thousands separators into numbers using sed. How can I do that?

Sample input/output: 29371923471239 should become 29.371.923.471.239.

3 Answers 3

2

Try this

echo "29371923471239" | sed -r ':A;s|([0-9]+)([0-9]{3})|\1,\2|g;t A'
29,371,923,471,239

This works by splitting the number into two parts, the last 3 digits and everything else. It then adds a , to the end of everything else and branches back to the start. You can see this working with

echo "29371923471239" | sed -r ':A;s|([0-9]+)([0-9]{3})|\1,\2|g'
29371923471,239
1

From: http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_007.html

sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'

echo "981273981723" | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' 981,273,981,723

1
  • 1
    An explanation is good for the benefit of your answer, not a reference to a webpage.
    – Arcege
    Feb 26, 2012 at 22:32
1

USE GHC-ONELINERS FOR A GREAT GOOD

$> echo -n 29371923471239 | ghc -e "import Data.List.Split" -e "putStrLn . reverse . intercalate \".\" . splitEvery 3 . reverse =<< getContents"
29.371.923.471.239

!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .