[bash] 문자열 변수의 N 번째 단어

Bash에서는 문자열 홀드의 N 번째 단어를 변수로 가져오고 싶습니다.

예를 들면 :

STRING="one two three four"
N=3

결과:

"three"

이 작업을 수행 할 수있는 Bash 명령 / 스크립트는 무엇입니까?



답변

echo $STRING | cut -d " " -f $N


답변

대안

N=3
STRING="one two three four"

arr=($STRING)
echo ${arr[N-1]}


답변

사용 awk

echo $STRING | awk -v N=$N '{print $N}'

테스트

% N=3
% STRING="one two three four"
% echo $STRING | awk -v N=$N '{print $N}'
three


답변

일부 명령문이 포함 된 파일 :

cat test.txt

결과 :

This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement

따라서이 명령문 유형의 네 번째 단어를 인쇄하려면 다음을 수행하십시오.

cat test.txt |awk '{print $4}'

출력 :

1st
2nd
3rd
4th
5th


답변

값 비싼 포크, 파이프, 바 시즘 없음 :

$ set -- $STRING
$ eval echo \${$N}
three

그러나 글 로빙을 조심하십시오.


답변

STRING=(one two three four)
echo "${STRING[n]}"


답변