【发布时间】:2010-06-09 12:10:31
【问题描述】:
在 Bash 中,我想通过变量获取字符串的第 N 个单词。
例如:
STRING="one two three four"
N=3
结果:
"three"
什么 Bash 命令/脚本可以做到这一点?
【问题讨论】:
标签: bash
在 Bash 中,我想通过变量获取字符串的第 N 个单词。
例如:
STRING="one two three four"
N=3
结果:
"three"
什么 Bash 命令/脚本可以做到这一点?
【问题讨论】:
标签: bash
echo $STRING | cut -d " " -f $N
【讨论】:
另一种选择
N=3
STRING="one two three four"
arr=($STRING)
echo ${arr[N-1]}
【讨论】:
IFS(内部字段分隔符)设置为 ':' 或其他内容而不是空格,请在尝试之前将其改回。
使用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
因此,要打印此语句类型的第 4 个单词:
awk '{print $4}' test.txt
输出:
1st
2nd
3rd
4th
5th
【讨论】:
没有昂贵的分叉,没有管道,没有 bashisms:
$ set -- $STRING
$ eval echo \${$N}
three
或者,如果你想避免eval,
$ set -- $STRING
$ shift $((N-1))
$ echo $1
three
但要注意通配(使用set -f 关闭文件名通配)。
【讨论】:
set -f 之后,如果不会全局扩展星号,使用set +f(默认)会。
STRING=(one two three four)
echo "${STRING[n]}"
【讨论】: