我们假设以下变量:
something=" abc def ghi"
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用参数扩展并仅省略abc. 我尝试了 10 种有意义的组合和另外 20 种随机组合。我得到的最接近的是:
echo ${something% *}
abc def
Run Code Online (Sandbox Code Playgroud)
这件事有可能实现吗?如果是这样,怎么办?谢谢。
一次 bash 扩展将会很困难。您可能对此感兴趣:
$ a=" abc def ghi"
$ [[ "${a}" =~ ([^\ ][^\ ]*) ]]
$ echo "${BASH_REMATCH[0]}"
Run Code Online (Sandbox Code Playgroud)
这实际上是搜索字符串中的所有单词BASH_REMATCH并将它们存储在数组中。更多信息请参见man bash部分[[ expression ]]。
您还可以将事物转换为数组:
$ a=" abc def ghi"
$ b=( $a )
$ echo "${b[0]}"
Run Code Online (Sandbox Code Playgroud)
或者你可以使用read
$ a=" abc def ghi"
$ read -r b dummy <<< "${a}"
$ echo "${b}"
Run Code Online (Sandbox Code Playgroud)
但是如果你真的想使用参数扩展,并且你允许使用extglob并且你不知道字符串中有多少个单词,你可以这样做
$ a=" abc def ghi"
$ shopt -s extglob
$ a=${a##*([ ])} #remove the spaces in the front
$ a=${a%% *} #remove everything from the first space onwards
$ echo "${a}"
Run Code Online (Sandbox Code Playgroud)