0

I have a script from a coworker that formats my prompt. It grabs my branch and formats with the code below using sed (note I hardcoded the branch name for testing):

echo "* master" | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1 /'

In an effort to learn more of what the script was doing, I was playing around with it. I noticed it prints the name of my branch "master" but it leaves the space before the branch name (" master"). I want to eliminate the space. I can't seem to do this though.

harpun
  • 3,932
  • 1
  • 33
  • 38
Kelly
  • 577
  • 7
  • 16
  • Unrelated to the regex issue, the way to find out the current branch (if any) is to use git's `symbolic-ref` sub-command on `HEAD`. For instance, `git symbolic-ref -q --short HEAD` prints the name of the current branch, or nothing at all if not on a branch (with an error message if not in a git tree at all). – torek Nov 25 '13 at 00:15

4 Answers4

2

You can simplify the problem by not using sed

echo "* master" | cut -c3-
Daniel
  • 6,858
  • 5
  • 40
  • 46
  • Thanks so much! That works! However, what is "cut" doing? I can't find documentation on it. – Kelly Nov 24 '13 at 22:39
2

maybe you are looking for this:

kent$  echo "* master" | sed 's/ \+//'                          
*master

this sed line removes the first occurrence of one or more spaces.

Kent
  • 173,042
  • 30
  • 210
  • 270
  • Thanks for the help. However, when I run this I still get the full expression with the space. – Kelly Nov 24 '13 at 22:40
2

Just remove the space before your \1. Probably you want to remove the space behind it as well.

echo "* master" | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
Felix
  • 106
  • 1
  • 4
  • Thanks! I couldn't figure out whether to use a '/s' or if it was just a space. I was really confused! – Kelly Nov 24 '13 at 23:56
0

the original sed is a bit strange compare to your hard coding branch

  1. It delete the line if it not start with a "*" and try to load a new one. Your branch is coming from a file or command with multi line ?
  2. It take end of line after "* ". It is simplier to just "remove" begin of line

    Your_source | sed -n '/[^*]/ {s/^* //p;q;}'

take only line starting with "* ", remove begin, print it and quit (no more than 1 line starting with "* " treated)

NeronLeVelu
  • 9,372
  • 1
  • 21
  • 41