Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether a string contains newlines by using the grep command?

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 '^.*$'
like image 791
eleven Avatar asked Nov 11 '12 21:11

eleven


1 Answers

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.

like image 127
Chris Seymour Avatar answered Nov 15 '22 08:11

Chris Seymour