Using the -c grep option to count lines that match this can be achieved. Note that the $ character matches the end of lines, not \n , and you can also see how double quotes around $test are important to keep line breaks.
test="one two three" echo $test | grep -c '$' 1 echo "$test" | grep -c '$' 3
You can also test against ^ beginning of a line or .* Anything, or as in your question, the entire line ^.*$ With the -c option.
How about wc for testing multi-line variables. wc -l prints the number of newlines:
echo "$test" | wc -l 3
Just like newlines you can also use wc to count the characters and words in the file (or the / stdout variable) with wc -m and wc -w respectively.
Or how to use tr to replace \n unique character not contained in a variable, for example:
echo "$test" | tr '\n' '_' one_two_three_
Then you can grep replace the replaced character, in this case _
Or even using cat -E
echo "$test" | cat -E one$ two$ three$
cat -E or --show-ends displays $ at the end of each line.
source share