As part of a makefile recipe, I want to repeatedly adjust a few lines in some text file txt.in. In particular, I want to update, among others, the third line which contains simply two numbers separated by a space. They should be formatted as 0.00 0.00. As such, I've included the code below in my makefile to test whether I can do this.

# Makefile to test for-loop

    for k in 1 2 3; do \
        let n="$$k*0.25"; \
        let m="$$n+0.25"; \
        sed -i "3s/.*/$$n $$m/" txt.in; \

This yields 0.7500000000 1.0000000000 as the end result. There may be more efficient ways to do this and I'd be happy to find out about those, but the thing I'd really like to find out is if there's a way to get the format right.


Pipe the output through

sed 's/\([0-9]\{1,\}\.[0-9][0-9]\)[0-9]*\>/\1/g'

to get the desired format. Effectively, your sed statement will change to:

sed -i "3s/.*/$$n $$m/" txt.in | sed -i 's/\([0-9]\{1,\}\.[0-9][0-9]\)[0-9]*\>/\1/g' txt.in; \
  • I see what you're getting at, but I'm afraid I still get the same result 0.7500000000 1.0000000000. Adding the line sed -i '3s/\([0-9]\{1,\}\.[0-9][0-9]\)[0-9]*\>/\1/g' txt.in; \ instead of using piping does work, any idea why this might be? – Wouter Jun 24 '14 at 14:34
  • I see the problem and have fixed the answer. The piping did not work on txt.in. – unxnut Jun 24 '14 at 14:56
  • That works entirely as desired, thanks! :) – Wouter Jun 24 '14 at 15:30

You can also use printf. This will give you zero padding for integer numbers even if your shell doesn't provide it:

o="$(printf "%.2f\n" "$$m")"
p="$(printf "%.2f\n" "$$n")"
sed -i "3s/.*/$$o $$p/" txt.in;

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.