在Bash中,我想通过变量获取字符串的第N个单词.
例如:
STRING="one two three four"
N=3
Run Code Online (Sandbox Code Playgroud)
结果:
"three"
Run Code Online (Sandbox Code Playgroud)
什么Bash命令/脚本可以做到这一点?
Ama*_*9MF 89
echo $STRING | cut -d " " -f $N
Run Code Online (Sandbox Code Playgroud)
aio*_*obe 57
替代
N=3
STRING="one two three four"
arr=($STRING)
echo ${arr[N-1]}
Run Code Online (Sandbox Code Playgroud)
jks*_*hah 28
运用 awk
echo $STRING | awk -v N=$N '{print $N}'
Run Code Online (Sandbox Code Playgroud)
测试
% N=3
% STRING="one two three four"
% echo $STRING | awk -v N=$N '{print $N}'
three
Run Code Online (Sandbox Code Playgroud)
小智 6
包含一些语句的文件:
cat test.txt
Run Code Online (Sandbox Code Playgroud)
结果:
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
Run Code Online (Sandbox Code Playgroud)
因此,要打印此语句类型的第四个单词:
cat test.txt |awk '{print $4}'
Run Code Online (Sandbox Code Playgroud)
输出:
1st
2nd
3rd
4th
5th
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89152 次 |
| 最近记录: |