I want to find the number of new lines in a string and then use this number in a while
loop as the limit.
I can find and write the number of lines using:
echo "$MY_STRING" | grep -c '$'
In order to have the number of lines as integer and use it in while loop I do this:
MYNUM="$MY_PEERS" | grep -c '$'
However, this line writes 0, which is not the number of lines in my string, immediately to the terminal. Moreover, I cannot use MYNUM
in a while
loop. (I use $MYNUM
in the while
) How can I obtain number of lines so that I can use it in a while
loop as the limit?
echo
is the issue here, useecho -e
to allow interpretation of\n
in the string.. or useprintf
as echo adds a\n
on its own, or perhapsecho -ne
will work... also,wc -l
would be an alternate togrep -c '$'
– Sundeep Mar 12 '17 at 05:04grep -c (all)
) is not the number of newline characters (wc -l
) if the last line is unterminated, although most 'good' data doesn't use an unterminated last line. – dave_thompson_085 Mar 12 '17 at 16:52