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.

  • Thanks for the sources, I'll look into them! – user323587 Jan 22 '19 at 17:30

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

  • 1
    Umm... Now you've made the code worse. The 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
  • 1
    Oh I didn't say my answer was better, I just figured out the problem :D – user323587 Jan 22 '19 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.