bash 字符串变量中的第 N 个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3005627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nth word in a string variable
提问by Nicolas Raoul
In Bash, I want to get the Nth word of a string hold by a variable.
在 Bash 中,我想通过变量获取字符串的第 N 个单词。
For instance:
例如:
STRING="one two three four"
N=3
Result:
结果:
"three"
What Bash command/script could do this?
什么 Bash 命令/脚本可以做到这一点?
回答by Amardeep AC9MF
echo $STRING | cut -d " " -f $N
回答by aioobe
An alternative
替代
N=3
STRING="one two three four"
arr=($STRING)
echo ${arr[N-1]}
回答by jkshah
Using awk
使用 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
回答by Akhiljith P B
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 :
因此,要打印此语句类型的第 4 个单词:
cat test.txt |awk '{print }'
Output :
输出 :
1st
2nd
3rd
4th
5th
回答by Jens
No expensive forks, no pipes, no bashisms:
没有昂贵的叉子,没有管道,没有 bashisms:
$ set -- $STRING
$ eval echo ${$N}
three
But beware of globbing.
但要小心通配。
回答by mnrl
STRING=(one two three four)
echo "${STRING[n]}"