grep -P不再起作用.如何重写搜索?
问题描述:
似乎新版本的OSX不再支持grep -P
,因此使我的某些脚本无法正常工作.
It looks like the new version of OSX no longer supports grep -P
and as such has made some of my scripts stop working.
var1=`grep -o -P '(?<=<st:italic>).*(?=</italic>)' file.txt`
我需要将grep捕获到变量中,并且需要使用零宽度断言以及\K
I need to capture the grep to a variable and I need to use the zero width assertions, as well as \K
var2=`grep -P -o '(property:)\K.*\d+(?=end)' file.txt`
任何其他选择都将不胜感激.
Any alternatives would be greatly appreciated.
答
如果您想做最少的工作,请更改
If you want to do the minimal amount of work, change
grep -P 'PATTERN' file.txt
到
perl -nle'print if m{PATTERN}' file.txt
并更改
grep -o -P 'PATTERN' file.txt
到
perl -nle'print $& while m{PATTERN}g' file.txt
所以您得到:
var1=`perl -nle'print $& while m{(?<=<st:italic>).*(?=</italic>)}g' file.txt`
var2=`perl -nle'print $& while m{(property:)\K.*\d+(?=end)}g' file.txt`
在您的特定情况下,您可以通过额外的工作来实现更简单的代码.
In your specific case, you can achieve simpler code with extra work.
var1=`perl -nle'print for m{<st:italic>(.*)</italic>}g' file.txt`
var2=`perl -nle'print for /property:(.*\d+)end/g' file.txt`