如何將字串與正規表示式匹配並有條件地使用捕獲組執行操作

如何將字串與正規表示式匹配並有條件地使用捕獲組執行操作

這裡的想法是將所有 git 儲存庫中的遠端從 http 更改為 ssh

find / -type d -name '.git' 2>/dev/null | xargs -I {} $SHELL -c \
'cd $(dirname {}) && echo $(pwd) > /tmp/log.log && git remote | \
perl -ne "if (`git config --get remote.$_.url` =~ m#https://(.*)/(username.*)#){`git remote remove $_ && git remote add $_ git\@$1:$2`}"

我想要做的是找到我的所有(perl 正規表示式中的使用者名稱)儲存庫並將它們切換為使用 ssh 而不是 http。我已經測試了 perl 腳本,它工作正常,但是當我在命令中使用它時,它會輸出這個

fatal: No such remote: remote syntax error at -e line 1, near "( =~" syntax error at -e line 1, near ";}" Execution of -e aborted due to compilation errors. xargs: /bin/zsh: exited with status 255; aborting

答案1

我不太確定你想要什麼(確切的預期命令是什麼),但是:

printf "%s\n" 'https://github.com/username/reponame.git' \
 '[email protected]:username/reponame' | perl -lne \
'if (m#https://(.*?)/(.*/)#) {print "git remote remove $_ && git remote add $_ git\@$1:$2"}'

應該要列印

git remote remove https://github.com/username/reponame.git && git remote add https://github.com/username/reponame.git [email protected]:username/

(如果您確定要執行命令,請將 變更print為)system


我更改了for r in xyz將 URL:s 輸入到 Perl 的標準輸入,如果你想在命令列上給出它們,你可以這樣做

perl -le '$_=shift; if (m#http://(.*?)/(.*/)#) {print "blah $_ $1:$2"}' http://foo.bar/user/something

將命令列參數刪除到(除非您使用 指定其他內容,否則$_隱式使用該參數)。m//$var =~ m//

另外,最好對@字串中的 進行轉義,因為它是數組變數的印記。

相關內容