bash 如何使用grep和regex从字符串中提取数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20770933/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:05:34  来源:igfitidea点击:

How to extract a number from a string using grep and regex

regexlinuxbashshellgrep

提问by MOHAMED

I make a cat of a file and apply on it a grepwith a regular expression like this

我制作了一个文件的 cat 并使用这样grep的正则表达式对其进行了应用

cat /tmp/tmp_file | grep "toto.titi\[[0-9]\+\].tata=55"

the command display the following output

该命令显示以下输出

toto.titi[12].tata=55

is it possible to modify my grep command in order to extract the number 12as displayed output of the command?

是否可以修改我的 grep 命令以提取数字12作为命令的显示输出?

回答by anubhava

You can grab this in pure BASH using its regex capabilities:

您可以使用其正则表达式功能在纯 BASH 中获取它:

s='toto.titi[12].tata=55'
[[ "$s" =~ ^toto.titi\[([0-9]+)\]\.tata=[0-9]+$ ]] && echo "${BASH_REMATCH[1]}"
12

You can also use sed:

您还可以使用sed

sed 's/toto.titi\[\([0-9]*\)\].tata=55//' <<< "$s"
12

OR using awk:

或使用 awk:

awk -F '[\[\]]' '{print }' <<<"$s"
12

回答by oyss

use lookahead

使用前瞻

echo toto.titi[12].tata=55|grep -oP '(?<=\[)\d+'
12

without perl regex,use sed to replace "["

没有 perl 正则表达式,使用 sed 替换“[”

echo toto.titi[12].tata=55|grep -o "\[[0-9]\+"|sed 's/\[//g'
12

回答by Bohemian

Pipe it to sedand use a back reference:

将其通过管道输送到sed并使用反向引用:

cat /tmp/tmp_file | grep "toto.titi\[[0-9]\+\].tata=55" | sed 's/.*\[(\d*)\].*//'