Report this

What is the reason for this report?

Using SED, stream editor, formatting

Posted on January 23, 2017

Using SED, stream editor, how can i properly format a string of numeric text characters to currency representation to include dollar sign, commas and decimal point.



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

This comment has been deleted

@chiavaccija

The following will convert a string of given numbers to proper format in terms of ensuring numbers are properly separated by a ,, though it won’t add the $ or round decimals up or down.

echo "1234567890" | \
sed -r '
  :L
  s=([0-9]+)([0-9]{3})=\1,\2=
  t L'

Output

1,234,567,890
echo "1234567890.99" | \
sed -r '
  :L
  s=([0-9]+)([0-9]{3})=\1,\2=
  t L'

Output

1,234,567,890.99

That being said, SED really isn’t the best option when it comes to formatting. You could easily achieve the same using any programming language without the need for regex (in most cases).

For example, with PHP, to format a number, you’d simply provide it to the number_format function.

<?php
$number = "12100.99";

echo number_format( $number ) . PHP_EOL;
echo number_format( $number, 2 ) . PHP_EOL;

Output

12,101
12,100.99

The . PHP_EOL is present to return output on a new line.

The first version will automatically round the given number up or down while the second version tells the function that we want to keep 2 decimal places (and not round).

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.