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

Suppose we have a test variable that contains a newline, for example \n . If I use the following command:

 echo "$test" | grep '\n' 

the result is not what I expect. The above grep only searches the test string if it contains the character 'n' and not a new line, because the character is '\' escape 'n'.

How to write grep command to search for a newline character in a specific line? FYI, the following is also wrong.

 echo "$test" | grep '^.*$' 
+4
source share
1 answer

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.

+7
source

Source: https://habr.com/ru/post/1445393/


All Articles