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
  1. perl -pi -e's/__LINE__/$./' txt
复制代码

作者: pengphy    时间: 2012-01-18 23:43
grep -n
作者: Perlvim    时间: 2012-01-18 23:49
  1. #!/usr/bin/perl

  2. use strict;
  3. use warnings;
  4. use 5.010;
  5. use File::Slurp qw(read_file);

  6. my $file = 'test.c';
  7. my $text = read_file $file;

  8. if ($text =~ m{__LINE__}) {
  9.     $text = replace_line_number($text);
  10. }

  11. say $text;

  12. sub replace_line_number {
  13.     my $text = shift;
  14.     my @lines = split /\n/, $text;
  15.     my $number = 1;
  16.     foreach my $line (@lines) {
  17.         $line =~ s/__LINE__/$number/g;
  18.         $number++;
  19.     }
  20.     my $new_text = join "\n", @lines;
  21.     return $new_text;
  22. }
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2