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

时间:2010-06-09 12:10:31

标签: bash

在Bash中,我想通过变量得到字符串的第N个字。

例如:

STRING="one two three four"
N=3

结果:

"three"

Bash命令/脚本可以做什么?

6 个答案:

答案 0 :(得分:84)

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

答案 1 :(得分:56)

替代

N=3
STRING="one two three four"

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

答案 2 :(得分:26)

使用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

答案 3 :(得分:3)

包含一些语句的文件:

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

答案 4 :(得分:2)

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

答案 5 :(得分:2)

没有昂贵的叉子,没有管道,没有基本原理:

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

但要注意全球化。