我有一个包含一句话的字符串,例如a="你好我的朋友"
。我想要提取前两个单词(这里应该是“你好我的”),并且知道单词数量可能会变化。我尝试过使用${a%% *}
,但是它只给出了第一个单词。
同样地���我需要提取整个句子去掉前两个单词。我该如何做到这一点?
您可以使用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
$ a="hello my dear friend"
$ [[ $a =~ ^([^ ]+ [^ ]+)\ ?(.*) ]]
$ echo "${BASH_REMATCH[1]}"
hello my
$ echo "${BASH_REMATCH[2]}"
dear friend
extglob
功能也可以使用匹配表达式作为排除条件:$ 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?
在任何Bourne shell或更高版本中,都可以使用Shell函数:
$ f2 () { echo "$1" "$2" }
$ frest () { shift; shift; echo "$*" }
$ a="hello my dear friend"
$ f2 $a
hello my
$ frest $a
dear friend