linux - 有没有办法检查子字符串是否在 Linux/Bash 脚本中的字符串中,并且在条件 if 语句中可以使用短行?
问题描述
我在用着
if[ "$wordCount" -gt 10 ]
要检查该行中是否有超过 10 个单词,但我怎样才能检查特定字符串,例如“Brown Cow”是否也在该行中?
因此,仅当该行的 wordCount 超过 10 并且在 $line 字符串中包含字符串“Brown Cow”时,条件才应该起作用。有没有办法在 Linux/Bash 中做到这一点?还是我需要一个多行或不同的条件类似案例来做到这一点?
解决方案
您可以在表达式中使用正则表达式或 glob 模式[[
。由于您要查找的字符串有空格,因此它需要在一个变量中以补偿解析器的限制:
phrase="Brown Cow"
if [[ $wordCount -gt 10 && $line =~ $phrase ]]; then
# Success
else
# Failure
fi
或者
# Note the *'s for a wildcard pattern match
phrase="*Brown Cow*"
if [[ $wordCount -gt 10 && $line = $phrase ]]; then
# Success
else
# Failure
fi
推荐阅读
- java - 二进制 XML 文件第 138 行:膨胀类 android.support.design.widget.NavigationView 时出错
- python - 3D 旋转猴头示例上的坐标
- sql - 将通配符用于连接、MS Access 的参数
- json - 在调用 JQ 时从变量中获取要更新的字段名称(不仅仅是值)
- streaming - Google Speech to Text 的 25 秒延迟
- typescript - 我如何等待一个元素有一些使用量角器的文本?
- javascript - 制作一个 HTML 元素数组
- r - 使用 expand.grid/crossing() 查找单个值和向量的组合,而不用元素分隔向量?
- c# - Xamarin.Android 中不接受 PKCS12 证书密码提示
- javascript - 使用 AJAX 将 .NET 对象传递给方法