我想使用以下正則表達式排除任何以“.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
它在外殼中返回“真”但“假”。有誰知道為什麼?
您可以顛倒邏輯並使所有包含.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="false"
else
Match_Result="true"
fi
echo $Match_Result
done;
輸出:
true
false
false
true
詳情:
(
- 開始一個捕獲組:
/[^/.]+
-/
然後是除/
and之外的一個或多個字符.
|
- 或者
\.ses
—— .ses
)
- 分組結束$
- 字符串的結尾。使用shopt -s nocasematch
/啟用不區分大小寫的版本shopt -u nocasematch
(請參閱Bash 中的不區分大小寫的正則表達式)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句