string中的第N个字
在Bash中,我想要得到一个string的第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}' 
testing
 % N=3 % STRING="one two three four" % echo $STRING | awk -v N=$N '{print $N}' three 
 STRING=(one two three four) echo "${STRING[n]}" 
没有昂贵的叉子,没有pipe道,没有bashisms:
 $ set -- $STRING $ eval echo \${$N} three 
但要小心globbing。