我有一個字符串,其中有一個像 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