【问题标题】:Open a file, search for a string and fill a string in another file打开一个文件,搜索一个字符串并将一个字符串填充到另一个文件中
【发布时间】:2014-02-13 14:56:49
【问题描述】:

我有 2 个文本文件。我“正在编写一个 perl 脚本,其中我需要在文本文件中找到“无法解析”字符串,然后提取具有该字符串的整行。在“/”之后提取该字符串的一部分并将该字符串存储在一个变量中。

然后我需要打开另一个文本文件,在这个文本文件中找到存储的字符串并替换该字符串。

    my $ldir = "/Android";
    $RESULTS_FILE = $ldir.'/'.'results.html';
    open OUT, ">>", $RESULTS_FILE;
    open(IN,"<logcat.txt");

    while(<IN>)
    {
            chomp;
            if( $_ =~ m/Unable to parse/ )
            {
                    my @string = split('/',$_);
                    print @string;
                    my $stream_name = $string[4];
                    while $srch(<OUT>)
                    {
                            chomp;
                            if( $srch =~ m/$stream_name/ )
                            {
                                  // How to replace the line here?
                            }
                    }
            }
    }

请帮忙。

问候, 拉姆基

【问题讨论】:

    标签: perl file


    【解决方案1】:

    您需要读取文件,用某些内容替换所有出现的目标字符串,然后再次保存该文件:

    #!/usr/bin/perl
    use strict;
    
    sub replace_string_in_file {
        my ( $source, $target, $filename ) = @_;
    
        my $filecontents = do {
                open my $fd, "<" $filename;
                local $/;
                <$fd>;
        };
    
        $filecontents =~ s/$source/$target/mg;
    
        open my $fd, ">", $filename;
        print $fd $filecontents;
        close($fd);
    }
    
    my $ldir = "/Android";
    $RESULTS_FILE = $ldir.'/'.'results.html';
    open(IN,"<logcat.txt");
    
    while(<IN>)
    {
            chomp;
            if( $_ =~ m/Unable to parse/ )
            {
                    my @string = split('/',$_);
                    print @string;
                    my $stream_name = $string[4];
    
                replace_string_in_file( $stream_name, "THIS IS THE REPLACEMENT", $RESULTS_FILE );
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-09
      • 2021-11-28
      • 2015-12-21
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多