Reputation: 11098
I need to do something very simple with sed
: I need to get the commit hash out of this string HEAD detached at 19d7ea9
.
Here's my attempt at it using sed
echo "HEAD detached at 19d7ea9" | sed 's/HEAD\ detached\ at\ \(.\+\)/\1/'
However, that command just doesn't work, and I can't quite figure out why. I know I can do it different like sed 's/HEAD\ detached\ at//
and have the same result. But I can't seem to figure out why the first method doesn't work.
Any answer will be appreciated. And this is my first time using sed
(I know I'm late to the party), so please overlook at noobie mistake.
EDIT: Thanks for all the answers. It seems like using the -E
flag is the most straightforward way to solve this.
I tried to follow @ooga's answer with another example, but that also failed miserably. Again, I can't figure out what I am doing wrong here:
EXAMPLE 2: I am trying to see whether the repo is ahead or behind remote, and by how many commits. Here's my code
status="On branch master Your branch is ahead of 'origin/master' by 1 commit. (use "git push" to publish your local commits) Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to..."
echo $status | sed -E 's/Your branch is (ahead|behind).+([0-9]+) comm)/\2 \1/'
Any further help on this topic is appreciated. I wonder why I can't get this whole sed
business right.
Upvotes: 0
Views: 208
Reputation: 203502
You got your answer about sed versions but FWIW in awk you just tell it to print the last space-separated field on the line:
awk '{print $NF}' file
Upvotes: 2
Reputation: 75555
It appears that +
is not a valid quantifier in POSIX Basic Regular Expression, but *
is, so the following works and should be portable even to OS X.
echo "HEAD detached at 19d7ea9" | sed 's/HEAD detached at \(.*\)/\1/'
Upvotes: 1
Reputation: 15501
Use "extended" (modern) regular expression syntax with the -E
flag (on OSX, or the -r
flag on GNU). That way not only do you have the +
quantifier, but you don't need to use backslashes in front of it or the parentheses.
sed -E 's/HEAD detached at (.+)/\1/'
Upvotes: 3