Suppose we have variable "test" which contains newline character, for example, \n
. If I use the following command:
echo "$test" | grep '\n'
the result is not what I expect. The above grep
command only search the test string whether contains character 'n' rather than newline since '\' escape 'n' character.
How should I write grep command to search the newline character in specific string? FYI, the following is not right too.
echo "$test" | grep '^.*$'
By using the -c
option of grep to count the lines that match this can be achieved. Note the $
character matches end of lines not \n
also see how the double quotes around $test
are important for preserving the line breaks.
test="one
two
three"
echo $test | grep -c '$'
1
echo "$test" | grep -c '$'
3
You could also test against ^
the start of the line or .*
anything, or as in your question, the whole line ^.*$
by using the -c
option.
How about wc
for testing multi-line variables. wc -l
prints the newline count:
echo "$test" | wc -l
3
Aswell as newlines
you can also use wc
to count characters
and words
in a file (or variable/stdout) with wc -m
and wc -w
respectively.
Or how about using tr
to replace \n
with a unique character not contained in the variable for instance:
echo "$test" | tr '\n' '_'
one_two_three_
You can then grep
for 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With