I am trying to update a variable within a for loop, sequentially adding to the variable, and then printing it to a series of file names.
Actually, I want to sequentially update a series of file, from a tmp file distTmp.RST
to sequentially dist1.RST
, dist2.RST
, etc..
The original distTmp.RST contains a line called "WWW". I want to replace the string with values called 21.5 in dist1.RST
, 22.5
in dist2.RST
, 23.5
in dist3.RST
, etc...
My code is as follows:
#!/bin/bash
wm=1
wM=70
wS=1
F=20.5
for W in {${wm}..${wM}..${wS}}; do
F=$(${F} 1 | bc)
echo ${F}
sed "s/WWW/"${F}"/g" distTmp.RST > dist${W}.RST
done
echo ${F}
========
But I am getting error message as follows:
change.sh: line 13: 20.5 1 | bc: syntax error: invalid arithmetic operator (error token is ".5 1 | bc")
Kindly suggest me a solution to the same.
CodePudding user response:
Kindly suggest me a solution to the same.
This might do what you wanted. Using a c-style for loop.
#!/usr/bin/env bash
wm=1
wM=70
wS=1
F=20.5
for ((w=wm;w<=wM;w =wS)); do
f=$(bc <<< "$F $w")
echo "$f"
sed "s/WWW/$f/g" distTmp.RST > "dist${w}.RST"
done
The error from your script might be because the order of expansion. brace expansion expansion happens before Variable does.
See Shell Expansion
CodePudding user response:
Use
F=$(echo ${F} 1 | bc)
instead of F=$((${F} 1 | bc))
. The doubled-up parentheses are what caused your error. Double parentheses weren't in the original code, but I get a different error saying 20.5: command not found
with the original code, so I tried doubling the parentheses and get the error in the question. Apparently, floating point numbers aren't supported by $(())
arithmetic evaluation expressions in Bash.