0

I have a string,

var=refs/heads/testing/branch

I want to get rid of refs/heads/ in the string using shell script, such that I have only:

var=testing/branch

Commands I tried (one per line):

echo $(var) | awk -F\\ {'print $2'} 
echo $var | sed -e s,refs/heads/,, 
echo "refs/heads/testing/branch" | grep -oP '(?<=refs/heads/\)\w+' 
echo "refs/heads/testing/branch" | LC_ALL=C sed -e 's/.*\\//' 
echo "refs/heads/testing/branch" | cut -d'\' -f2 
echo refs/heads/testing/branch | sed -e s,refs/heads/,, 
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Celestial
  • 139
  • 2
  • 12
  • What have you tried/tested/searched/experimented and that had failed, where ? – Gilles Quénot Jun 11 '20 at 19:46
  • See https://stackoverflow.com/questions/13210880/replace-one-substring-for-another-string-in-shell-script – zedfoxus Jun 11 '20 at 19:47
  • @GillesQuenot I tried 1) echo $(var) | awk -F\\ {'print $2'} 2) echo $temp_branch | sed -e s,refs/heads/,, 3) echo "varrandomcollege-nt\user90" | grep -oP '(?<=randomcollege-nt\\)\w+' echo "randomcollege-nt\user90" | LC_ALL=C sed -e 's/.*\\//' echo "randomcollege-nt\user90" | cut -d'\' -f2 echo randomcollege-nt\user90| sed -e s,randomcollege-nt\,, – Celestial Jun 11 '20 at 19:51
  • 1
    Add this to your original post – Gilles Quénot Jun 11 '20 at 19:52
  • 2
    Welcome to Stack Overflow! Please update your question to show what you have already tried in a [minimal, complete, and verifiable example](https://meta.stackoverflow.com/questions/261592) and add sample input and expected output. For further information, please see [how to ask good questions](https://stackoverflow.com/help/how-to-ask), and take the [tour of the site](https://stackoverflow.com/tour) :) – Gilles Quénot Jun 11 '20 at 19:53
  • How did you get `refs/heads/testing/branch` in the first place? There's probably a better way to get the desired branch name. – chepner Jun 11 '20 at 19:53
  • @chepner i get this as part of Azure devops pipeline variable $(System.PullRequest.SourceBranch) – Celestial Jun 11 '20 at 20:02

2 Answers2

0

there are lots of options out there ,try easy ones:

echo $var | cut -d "/"  -f 3,4
echo $var | awk -F"/" '{print $3"/"$4}'
change198
  • 1,647
  • 3
  • 21
  • 60
  • what is `echo $var` gives you? – change198 Jun 11 '20 at 20:14
  • did you define var before running these commands? This is what I did `var="refs/heads/testing/branch"` and then run either of the commands provided you as answers. would be better if you can show the output of `echo $var` – change198 Jun 11 '20 at 20:32
0

Shell parameter expansion: remove the prefix "refs/heads/" from the variable contents

$ var=refs/heads/testing/branch
$ echo "${var#refs/heads/}"
testing/branch
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • export: `testing/branch': not a valid identifier as I am running as export temp_branch=echo "${temp_branch#refs/heads/}" – Celestial Jun 11 '20 at 20:27