bash - 检查字符串是否包含换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9033053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash - check if string contains newline
提问by Valentin Milea
What is the simplestway 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.
我想检查换行符以确保只有一个文件匹配。
采纳答案by Jo So
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.
这避免了打印文件名而只打印换行符。
回答by choroba
You can use pattern matching:
您可以使用模式匹配:
[[ $FILE == *$'\n'* ]] && echo More than one line
回答by Shiplu Mokaddim
If $strcontains new line you can check it by,
如果$str包含新行,您可以检查它,
if [ $(echo "$str" | wc -l) -gt 1 ];
then
// perform operation if it has new lines
else
// no new lines.
fi

