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

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

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

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

관련 정보