我有一个字符串,其中有一个像 a="hello my dear friend"
中的一个句子。我想检索前两个单词(这里应该是“你好我的”),知道单词的数量可以变化。我试过${a%% *}
,但它只给我第一个。在bash中提取一个字符串的两个第一个字
同样,我需要提取整个句子,而没有两个第一个单词。我怎样才能做到这一点?
我有一个字符串,其中有一个像 a="hello my dear friend"
中的一个句子。我想检索前两个单词(这里应该是“你好我的”),知道单词的数量可以变化。我试过${a%% *}
,但它只给我第一个。在bash中提取一个字符串的两个第一个字
同样,我需要提取整个句子,而没有两个第一个单词。我怎样才能做到这一点?
可以使用BASH阵列此:
# construct an array delimited by whitespace
a="hello my dear friend"
arr=($a)
# first two words
echo "${arr[@]:0:2}"
hello my
# anything after first 2 words
echo "${arr[@]:2}"
dear friend
你可以读取字符串到一个数组,并使用一个切片:
$ read -ra words <<<"$a" && echo "${words[@]:2}"
dear friend
在另一个过程的成本,你也可以使用cut
:
$ cut -d' ' -f3- <<<"$a"
dear friend
这个行为有点不同,因为它分裂单个空格,而使用read的方法会消耗每个单词之间的任意数量的空格。
$ f2() { echo "$1" "$2" }
$ frest() { shift; shift; echo "$*" }
$ a="hello my dear friend"
$ f2 $a
hello my
$ frest $a
dear friend
壳牌功能在任何Bourne shell或以后对这项工作也可以使用匹配的表达作为排除:
$ shopt -s extglob
$ a="hello my dear friend. would you like a beer?"
$ b="${a#+(!()) +(!()) }"
$ echo "$b"
dear friend. would you like a beer?
$ echo "${a%$b}"
hello my
或从字符串的另一端:
$ c="${a% +(!()) +(!())}"
$ echo "$c"
hello my dear friend. would you like
$ echo "${a#$c}"
a beer?
您可以使用正则表达式捕捉到你想要的文字部分:
$ a="hello my dear friend"
$ [[ $a =~ ^([^ ]+ [^ ]+)\ ?(.*) ]]
$ echo "${BASH_REMATCH[1]}"
hello my
$ echo "${BASH_REMATCH[2]}"
dear friend
bash的extglob
功能可能
谢谢,它的作品,似乎是更简单的方法! – pioupiou1211
这种方法的缺点是您不能在字符串中保留空格。 – ghoti
是的,但由于OP说前2个“单词”,单词不能有空格 – anubhava