11

What is the simplest way to check if a string contains newline?

For example, after

FILE=$(find . -name "pattern_*.sh")

I'd like to check for newline to ensure only one file matched.

Chris Stryczynski
  • 30,145
  • 48
  • 175
  • 286
Valentin Milea
  • 3,186
  • 3
  • 28
  • 29

3 Answers3

17

You can use pattern matching:

[[ $FILE == *$'\n'* ]] && echo More than one line
choroba
  • 231,213
  • 25
  • 204
  • 289
12

If $str contains new line you can check it by,

if [ $(echo "$str" | wc -l) -gt 1 ];
then
     // perform operation if it has new lines
else
     // no new lines.
fi 
Evgeni Sergeev
  • 22,495
  • 17
  • 107
  • 124
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
3

To refer to your example: Note that filenames could contain newlines, too.

A safe way to count files would be

find -name "pattern_*.sh" -printf '\n' | wc -c

This avoids printing the filename and prints only a newline instead.

Jo So
  • 25,005
  • 6
  • 42
  • 59