在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
因此,要打印此语句的第4个单词类型:
cat test.txt |awk '{print $4}'
输出:
1st
2nd
3rd
4th
5th
STRING=(one two three four)
echo "${STRING[n]}"
没有昂贵的叉子,没有管道,没有基础:
$ set -- $STRING
$ eval echo \${$N}
three
但要注意全球化。