简体   繁体   中英

How to ensure only one file is returned by checking for newline

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.

您可以使用模式匹配:

[[ $FILE == *$'\n'* ]] && echo More than one line

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 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM