删除bash中的一部分字符串

时间:2019-07-19 09:33:55

标签: regex bash

我如何从refs/heads/中删除refs/heads/hotfix/sub_pag/105部分并退还剩余部分hotfix/sub_page/105

3 个答案:

答案 0 :(得分:1)

您可以使用cut

echo refs/heads/hotfix/sub_pag/105 | cut -d/ -f3-
  • -d指定定界符/在这种情况下
  • -f指定要保留的列(字段)。我们需要从第3列开始的所有内容。

或者,使用变量和参数替换:

x=refs/heads/hotfix/sub_pag/105
echo ${x#refs/heads/}
  • #从变量值的开头删除字符串。

答案 1 :(得分:1)

abc="refs/heads/hotfix/sub_pag/105”
abc=${abc##refs/heads/}

第二行中的参数扩展将删除该部分。

答案 2 :(得分:0)

我发现sed的目的是有效且显而易见的

sed 's/refs\/heads\///g'

用法示例

#!/bin/sh
long_ref="refs/heads/hotfix/sub_pag/105"  # normally from pipeline/Jenkins/etc.
echo "$long_ref"
short_ref=$(echo "$long_ref" | sed 's/refs\/heads\///g')
echo "$short_ref"

输出

% sh test.sh
refs/heads/hotfix/sub_pag/105
hotfix/sub_pag/105