I have this loop that allows me to deal only with certain time steps from a simulation:
let ALLSTEPS=820000
for ((step=20000; step <= ALLSTEPS; step =20000)); do
echo "Step: $step"
...
Within the loop I need to read in a row from each line of an external file. This is what I have:
i=$((step));
k=$(sed "${i}q;d" externalFile.txt)
echo ${k%}
This does not work because in the external file, my rows go: 1, 2, 3, 4, etc whereas "step" is "20000, 40000, 60000, ..."
I could set up another loop but that seems unwieldy and I wonder if there's a cleaner way to do it?
CodePudding user response:
You can use multiple variables per arithmetic for loop:
ALLSTEPS=820000
for ((i=1, step=20000; step <= ALLSTEPS; i , step =20000)); do
echo "Step: $step, i: $i"
done
CodePudding user response:
Rather than using sed
(which will read through the entire file, just to pick out a single line), why not use read
in the loop to read the next line each time through?
for ((step=20000; step <= ALLSTEPS; step =20000)); do
IFS= read -r k <&3 # Read the next line from the external file
echo "Step: $step, k: $k"
...
done 3<externalFile.txt
In the above, I used FD #3 for the file (the 3<
and <&3
stuff), to avoid conflicts with standard input if anything else in the loop reads from that.
(And the IFS=
and -r
stuff in the read
command are standard ways to tell read
not just read the raw lines, don't "helpfully" preprocess them.)