for (( a=1;a<=$(wc -l sedtest1);a++ ));do echo $a; done
Gives me an error:
-bash: ((: a<=21 sedtest1: syntax error in expression (error token is "sedtest1")
for (( a=1;a<=$(wc -l sedtest1);a++ ));do echo $a; done
Gives me an error:
-bash: ((: a<=21 sedtest1: syntax error in expression (error token is "sedtest1")
The output of wc -l sedtest1
will be something like:
21 sedtest1
So the test will become something like a <= 21 sedtest1
which is invalid.
Also, that does mean that the wc
command will be run for each iteration of the loop. If the content of the sedtest1
file doesn't change between each iteration, it would be better to save that number of line first in a variable outside the loop:
n=$(wc -l < sedtest1) # using redirection avoids the output containing the filename
for ((a = 0; a < n; a++)); do echo "$a"; done
I also suspect that you're trying to use a loop to process text in an inefficient and non-shell way. You may want to read Why is using a shell loop to process text considered bad practice?. Looping over each line of a file in that way is not the right way to go.
Nevermind I was just being incredibly stupid...
wc -l file
outputs as "x file".
All I had to do was this:
for (( a=1;a<=$(wc -l sedtest1|awk '{print $1}');a++ ));do echo $a; done
wc
and awk
will be invoked in each iteration of the loop. If the file is large, this would run very slowly. See Stéphane Chazelas' answer.
– Kusalananda
Jan 22 '19 at 17:16