在 Bash 中的单词上拆分字符串

Split a string on a word in Bash

我希望能够根据单词拆分字符串。本质上是一个多字符定界符。 例如,我有一个字符串:

test-server-domain-name.com

我希望保留 'domain' 之前的所有内容,因此输出将是:

test-server-

注意:我不能在 '-' 上剪切。我必须能够在术语 'domain' 之前进行剪切,因为字符串的格式会有所不同,但 'domain' 将始终存在并且我将始终希望捕获 'domain'.[=13 之前的元素=]

这在 bash 中可行吗?

使用 awk:

echo test-server-domain-name.com | awk -F 'domain' '{print }'

这将在 第一个 domain 找到:

cutat=domain
fqdm=test-server-domain-name.com

res=${fqdm%%${cutat}*}
echo $res

输出:

test-server-

如果字符串中有多个 domain 并且想在最后一个上剪切,请改用 res=${fqdm%${cutat}*}(一个 %)。


来自 Shell Parameter Expansion:

${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

惊人是正确的。

$ name=test-server-domain-name.com
$ echo $name                                  
test-server-domain-name.com
$ echo $name |awk -F '-domain-name.com' '{print }'
test-server