Linux 无法使用 sed 和 grep 提取捕获组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18892670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can not extract the capture group with neither sed nor grep
提问by Jim
I want to extract the value pair from a key-value pair syntax but I can not.
Example I tried:
我想从键值对语法中提取值对,但我不能。
我试过的例子:
echo employee_id=1234 | sed 's/employee_id=\([0-9]+\)//g'
But this gives employee_id=1234
and not 1234
which is actually the capture group.
但这给出了employee_id=1234
而不是1234
实际上哪个是捕获组。
What am I doing wrong here? I also tried:
我在这里做错了什么?我也试过:
echo employee_id=1234| egrep -o employee_id=([0-9]+)
but no sucess.
但没有成功。
回答by anubhava
1. Use egrep -o
:
1. 使用egrep -o
:
echo 'employee_id=1234' | egrep -o '[0-9]+'
1234
2. using grep -oP
(PCRE):
2.使用grep -oP
(PCRE):
echo 'employee_id=1234' | grep -oP 'employee_id=\K([0-9]+)'
1234
3. Using sed
:
3. 使用sed
:
echo 'employee_id=1234' | sed 's/^.*employee_id=\([0-9][0-9]*\).*$//'
1234
回答by Jotne
Using awk
使用 awk
echo 'employee_id=1234' | awk -F= '{print }'
1234
回答by Adrian Frühwirth
You are specifically asking for sed
, but in case you may use something else - any POSIX-compliant shell can do parameter expansion which doesn't require a fork/subshell:
您特别要求sed
,但如果您可能使用其他东西 - 任何符合 POSIX 的 shell 都可以进行参数扩展,而无需 fork/subshell:
foo='employee_id=1234'
var=${foo%%=*}
value=${foo#*=}
?
?
$ echo "var=${var} value=${value}"
var=employee_id value=1234
回答by jayflo
To expand on anubhava's answer number 2, the general pattern to have grep return onlythe capture group is:
为了扩展 anubhava 的答案2,让 grep仅返回捕获组的一般模式是:
$ regex="$precedes_regex\K($capture_regex)(?=$follows_regex)"
$ echo $some_string | grep -oP "$regex"
so
所以
# matches and returns b
$ echo "abc" | grep -oP "a\K(b)(?=c)"
b
# no match
$ echo "abc" | grep -oP "z\K(b)(?=c)"
# no match
$ echo "abc" | grep -oP "a\K(b)(?=d)"
回答by commander Ghost
use sed -E for extended regex
使用 sed -E 扩展正则表达式
echo employee_id=1234 | sed -E 's/employee_id=([0-9]+)//g'