![](/img/trans.png)
[英]Find/sed: How can I recursively search/replace a string in files but only for lines that match a particular regexp
[英]How to print the count of the match (nth match) in the substituted string in a find-replace regexp on a string in a stream using either sed or perl?
细节:
我正在使用tail -f读取传入流中的文件
我可以使用sed在流中查找和替换字符/字符串,例如:
tail -f a.log | sed 's/'`echo -e "\xnn"`'/'`echo "$(tput setaf 1)|sep|$(tput sgr0)"`'/g'
以上实现的是给我一个清晰的分隔符串的可视标记(在这种情况下是不可打印的十六进制字符nn,nn可能以05为例,用红色(在本例中)替换为彩色(通过tput) )string | sep |。
所以我得到了类似的东西
field **|sep|** field **|sep|** field **|sep|**
我想要的是
field **|sep#1|** field **|sep#2|** field **|sep#3|**
因此,要求是在替换字符串中将第n个匹配标记为(| sepn |,其中n是遇到的匹配的编号)
使用Perl能够动态评估替换,以跟踪所做的替换次数:
my $str='field **|sep|** field **|sep|** field **|sep|**';
my $str2='saodifuasd|sep|psaoidugfsdoif|sep|sdoiufd';
my $cnt;
$cnt=0; $str=~s/\|sep\|/"|sep#".$cnt++."|"/ge;
$cnt=0; $str2=~s/\|sep\|/"|sep#".$cnt++."|"/ge;
print "$str\n";
print "$str2\n";
结果:
field **|sep#0|** field **|sep#1|** field **|sep#2|**
saodifuasd|sep#0|psaoidugfsdoif|sep#1|sdoiufd
如您所见,您必须在每一行上手动重置分隔符计数器。
检查这是否有帮助,它在(g)awk中。
gawk -F 'sep' '{ a=1;while (a <= NF) {printf("%d:%s",a,$a); a++}print}'
#! /usr/bin/perl
#sed 's/'`echo -e "\x05"`'/'`echo "$(tput setaf 1)|sep|$(tput sgr0)"`'/g'
use warnings;
use strict;
use Term::ANSIColor;
use Term::ANSIColor qw(:constants);
while(<>) {
my $count=1;
#s/\x05/"|#".$count++."|"/ge;
s/\x05/colored("|#".$count++."|", 'RED')/ge;
print;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.