简体   繁体   中英

Align numbers using only sed

I need to align decimal numbers with the "," symbol using only the sed command. The "," should go in the 5th position. For example:

183,7 

    2346,7 

        7,999 

Should turn into:

  183,7 

 2346,7 

    7,999 

The maximum amount of numbers before the comma is 4. I have tried using this to remove spaces:

sed 's/ //g' input.txt > nospaces.txt

And then I thought about adding spaces depending on the number of digits before the comma, but I don't know how to do this using only sed.

Any help would be appreciated.

if you change your mind, here is an awk solution

$ awk -F, 'NF{printf "%5d,%-d\n", $1,$2} !NF' file

  183,7

 2346,7

    7,999

set the delimiter to comma and handle both parts as separate fields

试试这个:

gawk -F, '{ if($0=="") print ; else printf "%5d,%-d\n", $1, $2 }' input.txt

如果您使用的是GNU sed ,则可以执行以下操作

sed -r 's/([0-9]+),([0-9]+)/printf "%5s,%d" \1 \2/e' input.txt

Assuming that there is only one number on each line; that there are at most four digits before the , , and that there is always a , :

sed 's/[^0-9,]*\([0-9]\+,[0-9]*\).*/    \1/;s/.*\(.....,.*\)/\1/;'

The first s gets rid of everything other than the (first) number on the line, and puts four spaces before it. The second one deletes everything before the fifth character prior to the , , leaving just enough spaces to right justify the number.

The second s command might mangle input lines which didn't match the first s command. If it is possible that the input contains such lines, you can add a conditional branch to avoid executing the second substitution if the first one failed. With Gnu sed, this is trivial:

sed 's/[^0-9,]*\([0-9]\+,[0-9]*\).*/    \1/;T;s/.*\(.....,.*\)/\1/;'

T jumps to the end of the commands if the previous s failed. Posix standard sed only has a conditional branch on success, so you need to use this circuitous construction:

sed 's/[^0-9,]*\([0-9]\+,[0-9]*\).*/    \1/;ta;b;:a;s/.*\(.....,.*\)/\1/;'

where ta (conditional branch to a on success) is used to skip over a b (unconditional branch to end). :a is the label referred to by the t command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM