字符串变量中的第 N 个单词

在 Bash 中,我想得到由变量保存的字符串的第 N 个单词。

例如:

STRING="one two three four"
N=3

结果:

"three"

什么 Bash 命令/脚本可以做到这一点?

124431 次浏览
echo $STRING | cut -d " " -f $N

An alternative

N=3
STRING="one two three four"


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

Using awk

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

Test

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

No expensive forks, no pipes, no bashisms:

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

Or, if you want to avoid eval,

$ set -- $STRING
$ shift $((N-1))
$ echo $1
three

But beware of globbing (use set -f to turn off filename globbing).

A file containing some statements:

cat test.txt

Result:

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

So, to print the 4th word of this statement type:

awk '{print $4}' test.txt

Output:

1st
2nd
3rd
4th
5th