bash 两个分隔符之间的 grep 子字符串

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

grep substring between two delimiters

regexbashperlgrepbusybox

提问by Ulrik

I have a lot of bashscripts that use perlexpressions within grepin order to extract a substring between two delimiters. Example:

我有很多bash脚本使用其中的perl表达式grep来提取两个分隔符之间的子字符串。例子:

echo BeginMiddleEnd | grep -oP '(?<=Begin).*(?=End)'

The problem is, when I ported these scripts to a platform running busybox, 'integrated' grepdoes not recognize -P switch. Is there a clean way to do this using grepand regular expressions?

问题是,当我将这些脚本移植到运行的平台时busybox,“集成”grep无法识别 -P 开关。有没有一种干净的方法可以使用grepand来做到这一点regular expressions

Edit: There is no perl, sedor awkon that platform. It's a lightweight linux.

编辑:该平台上没有perl,sedawk。这是一个轻量级的linux

回答by anubhava

You can use awkwith custom field separator like this to get same output:

您可以awk像这样使用自定义字段分隔符来获得相同的输出:

echo 'BeginMiddleEnd' | awk -F 'Begin|End' '{print }'
Middle

回答by Vytenis Bivainis

Assuming there's no more than one occurrence per line, you can use

假设每行不超过一次,您可以使用

sed -nr 's/.*Begin(.*)End.*//p'

With grep and non-greedy quantifier you could also print more than one per line.

使用 grep 和非贪婪量词,您还可以每行打印多个。

回答by Mark Setchell

Use bashbuilt-in parameter substitution:

使用bash内置参数替换:

# grab some string from grep output
f=BeginMiddleEnd
middleend=${f/Begin/}    # do some substitution to lose "Begin"

echo $middleend
MiddleEnd

beginmiddle=${f%%End}    # strip from right end to lose "End"
echo $beginmiddle
BeginMiddle

Loads more examples here.

在此处加载更多示例。