In bash, how do I count the number of lines in a variable?
I have a variable which has a string stored in it and need to check if it has lines in it:
var=`ls "$sdir" | grep "$input"`
pseudo-code:
while [ ! $var's number of lines -eq 1 ]
do something
That's my idea on how to check it. echo $var | wc -l
doesn't work - it always says 1
, even though it has 3
.
echo -e
doesn't work as well.
Quotes matter.
echo "$var" | wc -l
The accepted answer and other answers posted here do not work in case of an empty variable (undefined or empty string).
This works:
echo -n "$VARIABLE" | grep -c '^'
For example:
ZERO=
ONE="just one line"
TWO="first
> second"
echo -n "$ZERO" | grep -c '^'
0
echo -n "$ONE" | grep -c '^'
1
echo -n "$TWO" | grep -c '^'
2