如何通过检查换行符确保只返回一个文件

发布于 2024-12-29 11:01:48 字数 143 浏览 2 评论 0原文

检查字符串是否包含换行符的最简单方法是什么?

例如,在

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

我想检查换行符以确保只有一个文件匹配之后。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧情别恋 2025-01-05 11:01:48

您可以使用模式匹配:

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

You can use pattern matching:

[[ $FILE == *
\n'* ]] && echo More than one line
北方的巷 2025-01-05 11:01:48

如果 $str 包含新行,您可以通过以下方式检查:

if [ $(echo "$str" | wc -l) -gt 1 ];
then
     // perform operation if it has new lines
else
     // no new lines.
fi 

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 
離殇 2025-01-05 11:01:48

参考您的示例:请注意,文件名也可以包含换行符。

计算文件数量的安全方法是

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

这避免打印文件名并仅打印换行符。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文