简体   繁体   中英

Why is sed regex substitution not working?

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.

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/'

您得到了有关sed版本的答案,但是FWIW在awk中只是告诉它在行上打印最后一个以空格分隔的字段:

awk '{print $NF}' file

在POSIX Basic正则表达式中+似乎不是有效的量词,而*则是* ,因此以下内容可以工作,甚至可以移植到OSX。

echo "HEAD detached at 19d7ea9" | sed  's/HEAD detached at \(.*\)/\1/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM