我正在尝试从其二进制文件中提取 U-Boot 版本以进行比较,
考虑我要搜索的确切字符串如下,
U-Boot 2013.07.010 (Mar 21 2016 - 12:07:48)
所以我用正则表达式写了如下命令,
strings uboot | grep "U-Boot \([0-9]\{4\}.[0-9]\{2\}.[0-9]\{3\}\ ([a-z]\{3\} [0-9]\{2\} [0-9]\{4\} - [0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\})\)"
但是我没有看到上述命令的任何输出,
我可以使下面的命令工作,它只通过比较版本而不是在字符串中查找日期来提取版本
strings uboot | grep "U-Boot \([0-9]\{4\}.[0-9]\{2\}.[0-9]\{3\}\)"
有人可以纠正/建议我在第一个命令中做错了什么吗?
有没有更好的方法来做同样的事情?
最佳答案
第一个命令中的正则表达式已损坏,您需要转义一些字符(例如点)才能正确匹配,还需要匹配月份,即 Mar
您需要 [A-Za-z ]{3}
但您只指定了 [a-z]{3}
您也可以使用 -o
开关来打印匹配的部分。来自 grep
的手册页:
-o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
要仅提取版本,请使用以下任何一个:
$ grep -oP "(?<=^U\-Boot\s)[0-9]+\.[0-9]+\.[0-9]+" <<< "U-Boot 2013.07.010 (Mar 21 2016 - 12:07:48)"
2013.07.010
$ grep -oP "(?<=^U\-Boot\s)[0-9]{4}\.[0-9]{2}\.[0-9]{3}" <<< "U-Boot 2013.07.010 (Mar 21 2016 - 12:07:48)"
2013.07.010
$ egrep -o "\b[0-9]{4}\.[0-9]{2}\.[0-9]{3}\b" <<< "U-Boot 2013.07.010 (Mar 21 2016 - 12:07:48)"
2013.07.010
$ egrep -o "\b[0-9]+\.[0-9]+\.[0-9]+\b" <<< "U-Boot 2013.07.010 (Mar 21 2016 - 12:07:48)"
2013.07.010
$
关于regex - U-Boot版本提取对比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36199085/