Shell脚本:如何检查字符串是否遵循某种模式?

时间:2012-03-15 09:00:19

标签: regex string shell comparison

如何检查字符串是否遵循某种模式?

例如,我有$ var存储" hello.txt"我要匹配的模式是" ^(。+)。txt $" (即任何有" [任何文字在这里] .txt"

2 个答案:

答案 0 :(得分:3)

您也可以使用shell glob模式:

if [[ "$var" == *.txt ]]; then ...

case "$var" in
  *.txt) do something ;;
  *) do something else ;;
esac

答案 1 :(得分:0)

使用bash builtin =〜你可以这样做:

if [[ "aaaa" =~ a+ ]]
 then
   echo "ok"
 else
  echo "no"
fi
相关问题