详细信息:
我正在使用tail -f读取传入流中的文件
我可以使用sed查找和替换流中的字符/字符串,如下所示:
tail -f a.log | sed 's/'`echo -e "\xnn"`'/'`echo "$(tput setaf 1)|sep|$(tput sgr0)"`'/g'上面实现的是为分隔符字符串(在本例中是不可打印的十六进制字符nn )提供了一个清晰的可视标记,例如,nn可能是05,用红色(在本例中)着色(通过tput)的字符串|sep|替换它。
所以我得到了像这样的东西
field **|sep|** field **|sep|** field **|sep|**我想要的是
field **|sep#1|** field **|sep#2|** field **|sep#3|**因此,要求在替换字符串中标记第n个匹配(|sepn|,其中n是no。遇到的匹配数)
发布于 2012-04-26 17:38:52
使用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如您所见,您必须手动重置每一行上的分隔符计数器。
发布于 2012-04-26 18:08:11
检查这是否有帮助,它在awk中。
gawk -F 'sep' '{ a=1;while (a <= NF) {printf("%d:%s",a,$a); a++}print}'发布于 2012-04-27 20:55:08
#! /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;
}https://stackoverflow.com/questions/10330719
复制相似问题