首页 > 解决方案 > 有没有办法检查子字符串是否在 Linux/Bash 脚本中的字符串中,并且在条件 if 语句中可以使用短行?

问题描述

我在用着

if[ "$wordCount" -gt 10 ]

要检查该行中是否有超过 10 个单词,但我怎样才能检查特定字符串,例如“Brown Cow”是否也在该行中?

因此,仅当该行的 wordCount 超过 10 并且在 $line 字符串中包含字符串“Brown Cow”时,条件才应该起作用。有没有办法在 Linux/Bash 中做到这一点?还是我需要一个多行或不同的条件类似案例来做到这一点?

标签: linuxbashif-statement

解决方案


您可以在表达式中使用正则表达式或 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


推荐阅读