Chinaunix
标题:
如何判定一个字符串在文本中的位置
[打印本页]
作者:
Perlvim
时间:
2012-01-18 23:37
标题:
如何判定一个字符串在文本中的位置
一个文本中,有许多字符。如何定位某个字符所在的行?
例如如下文本
1 空行
2 hello world __LINE__
3 hello world __LINE__
4 hello world __LINE__
5 hello world __LINE__
如何获取每个__LINE__ 字符串所在行的行号?
替换成
1 空行
2 hello world 2
3 hello world 3
4 hello world 4
5 hello world 5
作者:
kurri
时间:
2012-01-18 23:37
perl -pi -e's/__LINE__/$./' txt
复制代码
作者:
pengphy
时间:
2012-01-18 23:43
grep -n
作者:
Perlvim
时间:
2012-01-18 23:49
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use File::Slurp qw(read_file);
my $file = 'test.c';
my $text = read_file $file;
if ($text =~ m{__LINE__}) {
$text = replace_line_number($text);
}
say $text;
sub replace_line_number {
my $text = shift;
my @lines = split /\n/, $text;
my $number = 1;
foreach my $line (@lines) {
$line =~ s/__LINE__/$number/g;
$number++;
}
my $new_text = join "\n", @lines;
return $new_text;
}
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2