正規表現で文字列を一致させ、キャプチャグループを使用して条件付きで操作する方法

正規表現で文字列を一致させ、キャプチャグループを使用して条件付きで操作する方法

ここでのアイデアは、すべての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正規表現のユーザー名)リポジトリを見つけて、httpではなくsshを使用するように切り替えることです。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


URLをPerlのstdinに入力するように変更しましたfor r in xyz。コマンドラインでURLを指定したい場合は、次のようにします。

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

へのコマンドライン引数を削除します(で何か他のものを指定しない限り、$_によって暗黙的に使用されます)。m//$var =~ m//

また、@これは配列変数の記号なので、文字列内の をエスケープしたほうがよいでしょう。

関連情報