I wanted to loop over the lines of a text file a.txt
. I know that if the file has e.g. 6 lines, I can do:
for c in {1..6} ; do echo $c; done
which prints:
1
2
3
4
5
6
and I can count the number of lines as
wc -l a.txt | cut -f1 -d' '
which gives 2852
Now when trying to substitute the wc
count into the for loop as follows, the loop doesn't work:
for c in {1..$(wc -l ~/a.txt| cut -f1 -d' ')} ; do echo $c; done
Instead of printing the numbers from 1 to 2852, it prints:
{1..2852}
How can I fix the sub-shell usage in the above loop to get the correct sequence of numbers?
(
bash --version
is (Debian):
GNU bash, version 5.1.4(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2020 Free Software Foundation, Inc.
)
wc -l <~/a.txt
you get the count by itself and don't needcut
. And if you only want to print the numbers you don't need a for loop, you can just run theseq
program likeseq $(wc -l <~/a.txt)
. – dave_thompson_085 Mar 18 '23 at 04:38