문자열을 정규식과 일치시키고 캡처링 그룹을 사용하여 조건부로 작업을 수행하는 방법

문자열을 정규식과 일치시키고 캡처링 그룹을 사용하여 조건부로 작업을 수행하는 방법

여기서 아이디어는 모든 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//

@또한 배열 변수의 각인이므로 문자열에서 이스케이프 하는 것이 좋습니다 .

관련 정보