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]}
IFS':'을 (내부 필드 분리) 또는 대신 공백의 무언가를, 다시이를 시도하기 전에 변경합니다.
일부 명령문이 포함 된 파일 :
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
STRING=(one two three four)
echo "${STRING[n]}"