我想使用以下正則運算式排除任何以“.ses”結尾的檔案或沒有擴展名的檔案。它在命令列中運行良好,但在 shell (bash/ksh) 中不起作用。
正則運算式模式: "\.(?!ses\$)([^.] \$)"
檔案名示例:
"/test/path/test file with spaces.__1" (expected true)
"/test/path/test file with spaces.ses" (expected false)
"/test/path/test file with spaces" (expected false)
"/test/path/test file with spaces.txt" (expected true)
FILE_NAME="/test/path/test file with spaces.__1"
PATTERN_STR="\.(?!ses\$)([^.] \$)"
if [[ "${FILE_NAME}" =~ ${PATTERN_STR} ]]; then
Match_Result="true"
else
Match_Result="false"
fi
echo $Match_Result
它在外殼中回傳“真”但“假”。有誰知道為什么?
uj5u.com熱心網友回復:
我只會使用帶有合適 glob 的 case 陳述句:
case "${FILE_NAME##*/}" in
*.ses)
Match_Result=false
;;
*.*)
Match_Result=true
;;
*)
Match_Result=false
;;
esac
考慮使用陣列而不是做空白體操。
uj5u.com熱心網友回復:
您可以顛倒邏輯并使所有包含.ses在末尾或在最后一個/.之后不包含點的字串失敗。
然后,您可以使用此腳本:
#!/bin/bash
declare -a arr=("/test/path/test file with spaces.__1"
"/test/path/test file with spaces.ses"
"/test/path/test file with spaces"
"/test/path/test file with spaces.txt")
# true false false true
PATTERN_STR='(/[^/.] |\.ses)$'
for FILE_NAME in "${arr[@]}"; do
if ! [[ "$FILE_NAME" =~ $PATTERN_STR ]]; then
Match_Result="true"
else
Match_Result="false"
fi
echo $Match_Result
done;
輸出:
true
false
false
true
詳情:
(- 開始一個捕獲組:/[^/.]-/然后是除/and之外的一個或多個字符.
|- 或者\.ses——.ses
)- 分組結束$- 字串的結尾。
使用shopt -s nocasematch/啟用不區分大小寫的版本shopt -u nocasematch(請參閱Bash 中的不區分大小寫的正則運算式)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/365314.html
