bash : n 번째 출력 열을 얻는 가장 짧은 방법
작업 중에 bash의 일부 명령 (내 경우에는 svn stRails 작업 디렉토리 에서 실행) 에서 다음과 같은 열 형식의 출력이 반복적으로 발생한다고 가정 해 봅시다 .
? changes.patch
M app/models/superman.rb
A app/models/superwoman.rb
명령 출력 (이 경우 파일 이름)으로 작업하려면 두 번째 열을 다음 명령의 입력으로 사용할 수 있도록 일종의 구문 분석이 필요합니다.
내가하고있는 일은 awk두 번째 열을 얻는 데 사용하는 것입니다 . 예를 들어 모든 파일을 제거하려고 할 때 (일반적인 유스 케이스가 아닙니다) :
svn st | awk '{print $2}' | xargs rm
내가 이것을 많이 입력했기 때문에 자연스러운 질문은 : bash에서 이것을 달성하는 더 짧은 (따뜻한) 방법이 있습니까?
참고 : 구체적인 질문은 svn 워크 플로에 있지만 본질적으로 쉘 명령 질문입니다. 워크 플로우가 어리 석고 대안 적 접근 방식을 제안한다고 생각한다면 투표하지 않을 것입니다. 그러나 여기서 가장 중요한 방법은 bash에서 n 번째 열 명령 출력을 가장 짧은 방식으로 얻는 방법입니다. . 감사 :)
cut두 번째 필드에 액세스하는 데 사용할 수 있습니다 .
cut -f2
편집 : 죄송합니다. SVN이 출력에 탭을 사용하지 않는다는 것을 몰랐으므로 약간 쓸모가 없습니다. cut출력에 맞출 수는 있지만 약간 깨지기 쉽습니다. cut -c 10-작동하는 것과 같지만 정확한 값은 설정에 따라 다릅니다.
다른 옵션은 다음과 같습니다. sed 's/.\s\+//'
다음과 같은 것을 달성하십시오.
svn st | awk '{print $2}' | xargs rm
bash 만 사용하면 다음을 사용할 수 있습니다.
svn st | while read a b; do rm "$b"; done
물론 짧지는 않지만 조금 더 효율적이며 파일 이름의 공백을 올바르게 처리합니다.
나는 같은 상황에 처해 있었고이 별칭을 .profile파일에 추가했습니다 .
alias c1="awk '{print \$1}'"
alias c2="awk '{print \$2}'"
alias c3="awk '{print \$3}'"
alias c4="awk '{print \$4}'"
alias c5="awk '{print \$5}'"
alias c6="awk '{print \$6}'"
alias c7="awk '{print \$7}'"
alias c8="awk '{print \$8}'"
alias c9="awk '{print \$9}'"
다음과 같이 쓸 수 있습니다.
svn st | c2 | xargs rm
zsh를 사용해보십시오. 접미사 별명을 지원하므로 .zshrc에서 X를 다음과 같이 정의 할 수 있습니다.
alias -g X="| cut -d' ' -f2"
그럼 당신은 할 수 있습니다 :
cat file X
한 단계 더 나아가서 n 번째 열에 대해 정의 할 수 있습니다.
alias -g X2="| cut -d' ' -f2"
alias -g X1="| cut -d' ' -f1"
alias -g X3="| cut -d' ' -f3"
파일 "file"의 n 번째 열을 출력합니다. grep 출력 또는 더 적은 출력에도이 작업을 수행 할 수 있습니다. 이것은 매우 편리하고 zsh의 킬러 기능입니다.
한 단계 더 나아가서 D를 다음과 같이 정의 할 수 있습니다.
alias -g D="|xargs rm"
이제 다음을 입력 할 수 있습니다 :
cat file X1 D
파일 "file"의 첫 번째 열에 언급 된 모든 파일을 삭제합니다.
bash를 알고 있다면 zsh는 새로운 기능을 제외하고는 크게 변경되지 않습니다.
크리스 HTH
스크립트에 익숙하지 않은 것 같으므로 여기에 예가 있습니다.
#!/bin/sh
# usage: svn st | x 2 | xargs rm
col=$1
shift
awk -v col="$col" '{print $col}' "${@--}"
이 저장이되면 ~/bin/x하고 있는지 확인 ~/bin당신에 PATH(지금은 당신이 당신에 넣어해야 할 뭔가 .bashrc당신이 일반적으로 열 N을 추출하기위한 가장 짧은 명령이는) x n.
숫자가 아닌 인수 또는 잘못된 수의 인수 등으로 호출 된 경우 스크립트는 적절한 오류 검사를 수행해야합니다. 이 베어 본 필수 버전을 확장하면 단위 102가됩니다.
Maybe you will want to extend the script to allow a different column delimiter. Awk by default parses input into fields on whitespace; to use a different delimiter, use -F ':' where : is the new delimiter. Implementing this as an option to the script makes it slightly longer, so I'm leaving that as an exercise for the reader.
Usage
Given a file file:
1 2 3
4 5 6
You can either pass it via stdin (using a useless cat merely as a placeholder for something more useful);
$ cat file | sh script.sh 2
2
5
Or provide it as an argument to the script:
$ sh script.sh 2 file
2
5
Here, sh script.sh is assuming that the script is saved as script.sh in the current directory; if you save it with a more useful name somewhere in your PATH and mark it executable, as in the instructions above, obviously use the useful name instead (and no sh).
It looks like you already have a solution. To make things easier, why not just put your command in a bash script (with a short name) and just run that instead of typing out that 'long' command every time?
If you are ok with manually selecting the column, you could be very fast using pick:
svn st | pick | xargs rm
Just go to any cell of the 2nd column, press c and then hit enter
Note, that file path does not have to be in second column of svn st output. For example if you modify file, and modify it's property, it will be 3rd column.
See possible output examples in:
svn help st
Example output:
M wc/bar.c
A + wc/qax.c
I suggest to cut first 8 characters by:
svn st | cut -c8- | while read FILE; do echo whatever with "$FILE"; done
If you want to be 100% sure, and deal with fancy filenames with white space at the end for example, you need to parse xml output:
svn st --xml | grep -o 'path=".*"' | sed 's/^path="//; s/"$//'
Of course you may want to use some real XML parser instead of grep/sed.
참고URL : https://stackoverflow.com/questions/7315587/bash-shortest-way-to-get-n-th-column-of-output
'Programming' 카테고리의 다른 글
| LD_LIBRARY_PATH 및 LIBRARY_PATH (0) | 2020.06.18 |
|---|---|
| SQLite의 장단점 및 공유 환경 설정 (0) | 2020.06.18 |
| HTML5 캔버스 요소에 텍스트를 작성하려면 어떻게해야합니까? (0) | 2020.06.18 |
| 골란 난수 생성기 (0) | 2020.06.18 |
| 중첩 된 JSON 객체를 평면화 / 비편 성화하는 가장 빠른 방법 (0) | 2020.06.18 |