[英]Bash: Regex: Matching if a string is a remote host for rsync
我認為我在下面有一個很好的正則表達式行,它適用於我在 Regexbuddy 中所做的測試,但似乎在 bash 中不起作用。
我需要比我更了解正則表達式的人來幫助我。 ;)
關鍵是要對字符串是否包含 rsync 的遠程主機進行基本測試。 所以我們正在測試一些有效的東西,比如 username@host:/ 或 username@host:~/ (我也假設。/?)...
#!/bin/bash
test="foo@bar:/here/path/"
regex='^([\w-_.]*)@([\w-_.:]*):[~./]'
if [[ "${test}" =~ "${regex}" ]]; then
echo "yes, remote host"
else
echo "no, local"
fi
# filter for remote host by regex
# ^ begin at start of line, ( [ match underscore, word & number chars, dashes, fullstops ] in * repetition ) until first @ and then ( [ match underscore, word & number chars, dashes, fullstops, and colons] in * repetition ) until : and then at least [ ~ or . or / )
# so someone@host-whatever-123.com:/path/ will match
# someone_here123@192.168.0.1:~/path/ will match
# blah123.user@2001:db8:85a3:8d3:1319:8a2e:370:7348:./path/ will match
# user@wherever:path/ will not, and /anything@starting.com:with/a/slash will not match
# etc
有任何想法嗎?
有幾個問題:
$regex
變量不應在=~
之后引用,否則啟用非正則表達式字符串匹配\w
不應該使用,使用[:alnum:]
POSIX 字符 class 代替,匹配字母和數字-
方括號表達式中的第一個或最后一個字符應被正確解析為連字符。 我還會在模式中使用+
(1 個或多個)量詞而不是*
來在@
之前和之后強制執行至少一個字符。
您可以使用
test="foo@bar:/here/path/"
regex='^([[:alnum:]_.-]+)@([[:alnum:]_.:-]+):[~./]'
if [[ "$test" =~ $regex ]]; then
echo "yes, remote host"
else
echo "no, local"
fi
請參閱Bash 演示。
Bash 不支持像\w
這樣的字符類,看看這里https://tldp.org/LDP/abs/html/x17129.html部分 POSIX 字符類
在您的情況下,請嘗試將\w
替換為[:alnum:]
並且您必須刪除=~
右側的引號。
我對其進行了一些修改,但這對我有用:
[[ "foo@bar:/here/path/" =~ ^[-_\.[:alnum:]]+@[-_\.[:alnum:]]+:[~./] ]] && \
echo "Remote" || \
echo "Local"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.