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
-coption of grep to count the lines that match this can be achieved. Note the$character matches end of lines not\nalso see how the double quotes around$testare important for preserving the line breaks.You could also test against
^the start of the line or.*anything, or as in your question, the whole line^.*$by using the-coption.How about
wcfor testing multi-line variables.wc -lprints the newline count:Aswell as
newlinesyou can also usewcto countcharactersandwordsin a file (or variable/stdout) withwc -mandwc -wrespectively.Or how about using
trto replace\nwith a unique character not contained in the variable for instance:You can then
grepfor the replaced character, in this case_Or even using
cat -Ecat
-Eor--show-endsdisplays$at the end of each line.