3

There seems to be a number of neat and simple methods for rounding all numbers in a column to 1 decimal place, using awk's printf or even bash's printf. However I can't find an equally simple method for just reducing all numbers in a column to 1 decimal place (but not round up). The simplest method for sorting this at the moment would be to round to 2 decimal places and then remove the last character from every line in column 1. Anyone got a better method for this? An example input and output would be as follows:

Input

123.434    
1456.8123  
2536.577    
345.95553  
23643.1454  

Output

123.4    
1456.8  
2536.5    
345.9  
23643.1 
9

easy enough with grep

$ cat ip.txt 
123.434
1456.8123
2536.577
345.95553
23643.1454    

$ grep -o '^[0-9]*\.[0-9]' ip.txt 
123.4
1456.8
2536.5
345.9
23643.1
  • ^ start of line
  • [0-9]* zero or more digits
  • \. match literal dot character
  • [0-9] match a digit
  • since -o option of grep is used, only matched portion is printed, effectively removing remaining characters

If there are other columns, use sed

$ cat ip.txt 
123.434 a
1456.8123 b
2536.577 c
345.95553 d
23643.1454 e

$ sed -E 's/^([0-9]*\.[0-9])[0-9]*/\1/' ip.txt
123.4 a
1456.8 b
2536.5 c
345.9 d
23643.1 e
  • -E use extended regex
  • required pattern is captured in () and \1 used in replacement section
  • [0-9]* after the capture group gets deleted

Further reading:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.