文字列を正規表現と照合し、キャプチャグループを使用して条件付き操作を実行する方法

文字列を正規表現と照合し、キャプチャグループを使用して条件付き操作を実行する方法

ここでのアイデアは、すべての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の標準入力に変更しましたfor r in xyz。コマンドラインに入力するには、次のようにします。

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

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

@また、配列変数の刻印なので、文字列からエスケープすることをお勧めします。

おすすめ記事