sed substitution

Hi everyone,

I need very simple sed command to change a parameter in a text file.

I have a line in this text which is like

set xx 0.5

A program reads this file and does some algebraic calculations. So to make a parameter scan I need to change the value of xx. I thought I can do this with a simple sed command in a shell loop. so the shell simply will look like

#!/bin/sh
xx=0.0
for ((i=0; i<=10; i++))
do xx = xx + i*0.5

% here comes the sed command which substitutes the existing value of xx with the one set above, and afterwards runs the program which reads that text file

done

thanks for all the help

Not sure I understand. The sed command will not run a program to read a text file. And if I interpret your request correctly, you want the text file to be modified to look like set 0.0 0.5 in the first loop, in which i is 0 and thus xx = 0.0 . Why do you need the file at all, when you can set xx within the shell itself?

ok, first of all i don't need sed to run the program, running the program comes after I change the parameter, forget about running the program. Second, I want the text file to be modified to look like
after the 1st iteration

set xx 0.0

after 2nd iteration

set xx 0.5

after 3rd iteration

set xx 1.0

etc.

Try

sed -i "s/^set xx .*/set xx $xx/" file

Pls note that the -i option is controversially discussed in this forum.

1 Like
sed -i 's/^\(set xx \)[0-9.][0-9.]*/\1'$xx'/' file

Maybe you can pass an input stream to your program?
It is more efficient to have

sed 's/^\(set xx \)[0-9.][0-9.]*/\1'$xx'/' file | your_program

thanks RudiC, this works very well. If you don't mind I would like to ask another simple question.

now I need to set a condition, after I run the program it produces an output file. Somewhere in this output
there is a line that looks like

#  Integrated weight  :  .60573E+01

in my shell script I need to read this line and if that number is in certain interval continue to do further calculations, if not skip to next iteration. So how can I write this if .. else statement?

This is one way:

n1=$(printf "%f" ".60573E+01")
n2=6
if (( $(bc -l <<< "$n2 > $n1") )); then
  echo n2 gt n1
else
  echo n2 ngt n1
fi

For example:

$ n2=6

$ if (( $(bc -l <<< "$n2 > $n1") )); then   echo n2 gt n1; else   echo n2 ngt n1; fi
n2 ngt n1

$ n2=7

$ if (( $(bc -l <<< "$n2 > $n1") )); then   echo n2 gt n1; else   echo n2 ngt n1; fi
n2 gt n1

Again, your context is not quite clear to me. If I guess correctly, you might want to try

awk -F: '/^#  Integrated weight :/  {if ($2+0 >= LOWER && $2+0 <= UPPER) exit; else exit 1}' LOWER=6 UPPER=8 file && do_calculations

Replace the constants for upper and lower limit with your variables if need be.