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`