下面圍繞“判斷字符串是否以.txt結尾”展開。轉變一下也同樣適用於“判斷字符串是否以.txt開頭”。
通用的方法
# 方法一、使用grep命令
#!/bin/sh str="/path/to/foo.txt" # 使用if語句 if echo "$str" | grep -q -E '\.txt$' then echo "true" else echo "false" fi # 寫成一行 echo "$str" | grep -q -E '\.txt$' && echo true || echo false grep -q -E '\.txt$' <<< "$str" && echo true || echo false
# 方法二、使用expr命令
#!/bin/sh str="/path/to/foo.txt" # 使用if語句 if expr "$str" : '.*\.txt$' &>/dev/null then echo "true" else echo "false" fi # 寫成一行 expr "$str" : '.*\.txt$' &>/dev/null && echo true || echo false
# 方法三、使用case指令
#!/bin/sh str="/path/to/foo.txt" case "$str" in *.txt ) echo "true";; * ) echo "false";; esac
# 其他方法
還可以使用AWK、SED,這里就不再介紹了,方法和上面是類似的。
特定於Shell的方法
BASH
#!/bin/bash # BASH中的正則表達式 [[ "/path/to/foo.txt" =~ .*txt$ ]] && echo "true" || echo "false" # BASH的特殊語法 [[ "/path/to/foo.txt" = *txt ]] && echo "true" || echo "false"
相關文章
「Shell」- 在腳本中,獲取腳本所在路徑
「Sehll」- 重復字符串
參考文獻
How do I do if(string.endsWith("/")) in shell
Bash String Comparison: Find Out IF a Variable Contains a Substring