-1

how do i remove refs/heads/ part from refs/heads/hotfix/sub_pag/105 and return the reamining part hotfix/sub_page/105?

Raaz
  • 1,578
  • 2
  • 22
  • 46
  • 2
    The question is clear tbh, doesn’t deserver so many downvotes. But yea if so many people feel that, please specify that `refs/heads/` and the other two are strings or strings assigned to a variable. – Mihir Luthra Jul 19 '19 at 09:42
  • @Mihir I think [this](https://duckduckgo.com/?q=stackoverflow+bash+remove+substring&t=ffsb&ia=web) explains the downvotes. That said, the proper course of action would be to close with a duplicate – Aaron Jul 19 '19 at 09:57
  • 1
    @Aaron, agreed but at the same time its nice to write a short comment explaining reason of downvote. (would help viewers and the OP) – Mihir Luthra Jul 19 '19 at 10:01
  • Also it's unclear whether the part to remove is always the same (in which case, [this](https://stackoverflow.com/questions/16623835/remove-a-fixed-prefix-suffix-from-a-string-in-bash) is an appropriate duplicate) or the string must be removed up to the second slash, with varying words in between – Aaron Jul 19 '19 at 10:01

3 Answers3

3

You can use cut:

echo refs/heads/hotfix/sub_pag/105 | cut -d/ -f3-
  • -d specifies the delimiter, / in this case
  • -f specifies which columns (fields) to keep. We want everything from column 3 onwards.

Or, use variables and parameter substitution:

x=refs/heads/hotfix/sub_pag/105
echo ${x#refs/heads/}
  • # removes the string from the beginning of the variable's value.
choroba
  • 216,930
  • 22
  • 195
  • 267
1
abc="refs/heads/hotfix/sub_pag/105”
abc=${abc##refs/heads/}

The parameter expansion in the second line would remove that part.

Mihir Luthra
  • 5,113
  • 2
  • 12
  • 35
0

I've found sed to be effective and obvious in purpose

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

Usage example

#!/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"

output

% sh test.sh
refs/heads/hotfix/sub_pag/105
hotfix/sub_pag/105
ti7
  • 12,648
  • 6
  • 30
  • 60