我需要匹配这个替换命令:
whatever__MATCH_THIS__whateverwhatever__AND_THIS__whateverwhatever
我正在尝试:
sed -e 's/__\(.*\)__/\{{\1}}/g' myfile
但这是热切地匹配__MATCH_THIS__whateverwhatever__AND_THIS__,产生:
whatever{{MATCH_THIS__whateverwhatever__AND_THIS}}whateverwhatever
但我想:
whatever{{MATCH_THIS}}whateverwhatever{{AND_THIS}}whateverwhatever
如何在匹配部分中指定要排除的字符串?我知道如何排除一个字符(例如[^ a])但不知道如何排除字符串.
解决方法
你需要的是一个非贪婪的正则表达式,但不幸的是sed不允许这样做.但是,它可以在perl中完成.
perl -pe 's|__(.*?)__|{{$1}}|g' <myfile
星号后面的问号表示匹配器是非贪婪的,所以不是采用它能找到的最长的匹配字符串,而是最短的.
希望有所帮助.
如果你想把它放在一个perl脚本而不是在命令行上运行,那么这样的事情就可以完成这项工作:
#! /usr/bin/perl -w use strict; # Habit of mine use 5.0100; # So we can use 'say' # Save the matching expression in a variable. # qr// tells us it's a regex-like quote (http://perldoc.perl.org/functions/qr.html) my $regex = qr/__(.*?)__/; # Ordinarily,I'd write this in a way I consider to be less perl-y and more readable. # What it's doing is reading from the filename supplied on STDIN and places the # contents of the file in $_. Then it runs the substitution on the string,before # printing out the result. while (<>) { $_ =~ s/$regex/{{$1}}/g; say $_; }
用法很简单:
./regex myfile whatever{{MATCH_THIS}}whateverwhatever{{AND_THIS}}whateverwhatever
这是Perl,有一百万种方法可以做到!