在Bash中,我想通过变量获取字符串的第N个字。
例如:
STRING="one two three four"
N=3
结果:
"three"
什么Bash命令/脚本可以做到这一点?
在Bash中,我想通过变量获取字符串的第N个字。
例如:
STRING="one two three four"
N=3
结果:
"three"
什么Bash命令/脚本可以做到这一点?
Answers:
echo $STRING | cut -d " " -f $N
替代
N=3
STRING="one two three four"
arr=($STRING)
echo ${arr[N-1]}
IFS
(内部字段分隔符)设置为':'或其他内容(而不是空格),请在尝试此操作之前将其更改回去。
一个包含一些语句的文件:
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
STRING=(one two three four)
echo "${STRING[n]}"