字符串变量中的第N个单词

问题描述 投票:69回答:6

在Bash中,我想通过变量获取字符串的第N个单词。

例如:

STRING="one two three four"
N=3

结果:

"three"

什么Bash命令/脚本可以做到这一点?

bash
6个回答
84
投票
echo $STRING | cut -d " " -f $N

56
投票

替代

N=3
STRING="one two three four"

arr=($STRING)
echo ${arr[N-1]}

26
投票

使用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

3
投票

包含一些语句的文件:

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

2
投票
STRING=(one two three four)
echo "${STRING[n]}"

2
投票

没有昂贵的叉子,没有管道,没有基础:

$ set -- $STRING
$ eval echo \${$N}
three

但要注意全球化。

© www.soinside.com 2019 - 2024. All rights reserved.