How cut one character after the dot in a shell script variables

Viewed 35

I need to remove all characters after the first one after the dot:

example:

the temperature is 28.34567 C°

I need only 28.3

I've tried with cut -d'.' -f1 but cut all after the dot..

Thanks a lot

4 Answers

If you are using Bash:

$ var=23.123
$ [[ $var =~ [0-9]*(\.[0-9]{,1})? ]] && echo ${BASH_REMATCH[0]}

Output:

23.1

You could add this line to your script if you have python3+

python -c "print(f\"{28.34567:.1f}\")"

This solution rounds the result (ceil)

Output:

28.3

There are a few ways to do this, each with its own issues. The trivial solution is sed. Something like:

$ echo "the temperature is 28.37567 C°" | sed -e 's/\([[:digit:]]\.[0-9]\)[0-9]*/\1/g'
the temperature is 28.3 C°

but you probably don't want truncation. Rounding is probably more appropriate, in which case:

$ echo "the temperature is 28.37567 C°" | awk '{$4 = sprintf("%.1f", $4)}1'
the temperature is 28.4 C°

but that's pretty fragile in matching the 4th field. You could add a loop to check all the fields, but this gives the idea. Also note that awk will squeeze all your whitespace.

2 brute force ways, depending on whether u wanna keep the celsius sign or not :

mawk '$!_=int(10*$_)/10' <<<'28.34567 C°'

28.3 C°

mawk '$!NF=int(10*$_)/10' <<<'28.34567 C°'

28.3

Related