kuruvi
kuruvi

Reputation: 653

awk reduce decimals for a single multiple input values

I want to transform the following

82.77, 69.30, 43.75, 33.44, 26.88, 26.83, 24.89, 24.88, 24.74, 23.07, 19.31

into

82.8, 69.3, 44.0, 33.4, 26.8, ...

I think awk seems to be the easy way to do this. The following does work for a single input value

echo 123.45567 | awk '{printf("%.1f\n", $1)}'

How can I do this for the above multiple input values with the space delimiter with awk or is there any better way to do this? Yesterday I was trying with java script which didn't work.

Upvotes: 1

Views: 113

Answers (4)

Chris Seymour
Chris Seymour

Reputation: 85775

Just loop over each field:

$ awk  -F', ' '{for(i=1;i<=NF;i++)printf "%.1f%s",$i,(i==NF?RS:FS)}'

By setting the field separator to be , (a comma followed by a space) the input format is preserved in the output. The condition (i==NF?RS:FS) checks if we have reached the last field in the record and separates the output accordingly.

Upvotes: 2

anubhava
anubhava

Reputation: 785008

Use it like this:

s='82.77, 69.30, 43.75, 33.44, 26.88, 26.83, 24.89, 24.88, 24.74, 23.07, 19.31, 17.51.'
awk '{printf("%.1f\n", $1)}' RS=, <<< "$s"
82.8
69.3
43.8
33.4
26.9
26.8
24.9
24.9
24.7
23.1
19.3
17.5

Upvotes: 2

Raymond Hettinger
Raymond Hettinger

Reputation: 226256

Q: how can I do this for the above multiple input values with the space delimiter with awk

A: Try setting the RS record separator to a space:

echo '82.77 69.30 43.75 33.44 26.88 26.83 24.89 24.88 24.74 23.07 19.31 17.51' \ 
| awk 'BEGIN{RS=" "} {printf("%.1f\n", $1)}' 
82.8
69.3
43.8
33.4
26.9
26.8
24.9
24.9
24.7
23.1
19.3
17.5

Upvotes: 1

Jotne
Jotne

Reputation: 41456

Using awk, you can loop trough all fields.

awk '{for (i=1;i<=NF;i++) printf("%.1f, ",$i);print ""}' file
82.8, 69.3, 43.8, 33.4, 26.9, 26.8, 24.9, 24.9, 24.7, 23.1, 19.3, 17.5,

Upvotes: 2

Related Questions