如何将字符串与正则表达式匹配并有条件地使用捕获组执行操作

如何将字符串与正则表达式匹配并有条件地使用捕获组执行操作

这里的想法是将所有 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//

另外,最好对@字符串中的 进行转义,因为它是数组变量的印记。

相关内容