Marius Marius - 2 months ago 14
Bash Question

Replacing text with sed in shell

Like a number of other questers on here, I'm attempting to use sed to replace text inside of a file. This is in the context of a sh script I'm using to run an analysis code (the executable: "turns2d_over") a number of times with a slight modification to the inputs (contained in the file "steady") after each run. There is a specific line that I'm trying to replace that reads as follows where X.X is a number:

ALFA = X.X EXPLANATION

However...instead of replacing ALFA = X.X with ALFA = Y.Y (a different number), sed either does nothing or, in the case I've put in below (which is a copy of my current sh script), it deletes ALL text in the entire file...which is rather unhelpful.

TOT_VALS=9
ALPHAS[1]=-2.0
ALPHAS[2]=0.0
ALPHAS[1]=2.2
ALPHAS[4]=4.5
ALPHAS[5]=6.3
ALPHAS[6]=8.3
ALPHAS[7]=10.2
ALPHAS[8]=12.2
ALPHAS[9]=14.4

cd ./naca0008

for VAL in $(seq 1 $TOT_VALS); do
sed -n -i 's/ALFA = .*/ALFA = '${ALPHAS[$VAL]}'/g' steady

./turns2d_over<steady

mv 'fort.1' 'grid_in' # rename input grid to save from bulk move
mv 'fort.8' 'fort.q' # rename soln & grid outputs
mv 'fort.9' 'fort.g'
mkdir ./'alfa='${ALPHAS[$VAL]}/; mv 'fort.'* *'.dat' $_ # move files
cp 'steady' $_
mv 'grid_in' 'fort.1' # ready input grid for next run
done


So what's going on?

Answer

You either need to remove the -n or add a p at the end of your sed command. The -n means sed won't automatically print the pattern space (and the p will print out the current match).

If you want sed to leave the rest of the file (steady) alone, then remove the -n.

sed -i 's/ALFA = .*/ALFA = '${ALPHAS[$VAL]}'/g' steady

If you want sed to delete the rest of the file (steady) and only print the matching ALFA line, add p like this:

sed -n -i 's/ALFA = .*/ALFA = '${ALPHAS[$VAL]}'/gp' steady