「Shell」- 判斷字符串結尾 @20210121

下面圍繞「判斷字符串是否以.txt結尾」展開。轉變一下也一樣適用於「判斷字符串是否以.txt開頭」。 html

通用的方法

# 方法1、使用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

# 方法2、使用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

# 方法3、使用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"

參考文獻

相關文章
相關標籤/搜索