首页 > 解决方案 > 从字符串中第二次出现的破折号中提取字符

问题描述

我有一个字符串“ apple-rose-orange-21-X-84 ”;我需要使用 shell 脚本在第二次出现“ - ”之后提取字符串。

答案应该是orange-21-X-84

我将如何在 shell 脚本中执行此操作,我尝试了多种方法,但找不到答案。

标签: bashshellsh

解决方案


shell only solution:

string='apple-rose-orange-21-X-84'
echo ${string#*-*-}

See 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 the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘<em>’, 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 ‘</em>’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.


推荐阅读