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
grep substring between two delimiters
提问by Ulrik
I have a lot of bash
scripts that use perl
expressions within grep
in 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' grep
does not recognize -P switch. Is there a clean way to do this using grep
and regular expressions
?
问题是,当我将这些脚本移植到运行的平台时busybox
,“集成”grep
无法识别 -P 开关。有没有一种干净的方法可以使用grep
and来做到这一点regular expressions
?
Edit:
There is no perl
, sed
or awk
on that platform. It's a lightweight linux
.
编辑:该平台上没有perl
,sed
或awk
。这是一个轻量级的linux
。
回答by anubhava
You can use awk
with 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 bash
built-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.
在此处加载更多示例。