简体   繁体   English

Perl 脚本修改一个文件,从第二个文件中取值

[英]Perl script to modify one file taking values from second file

I've written a Perl Script which processes two files, File 1 contains some text in which 'ABC' needs to be replaced with the list of values present in 2nd text file.我编写了一个处理两个文件的 Perl 脚本,文件 1 包含一些文本,其中“ABC”需要替换为第二个文本文件中存在的值列表。

File1.txt :文件 1.txt :

Name     -> ABC

Record   -> Exists

Presence -> Existing_ABC

File2.txt :文件 2.txt :

John

Claude

Kepler

Shane

Austin

I want to replace 'ABC' from File1 with John then the original File1 should be taken again and 'ABC' should get replaced with Claude and merged with the first iteration and so on in the similar way till the last entry of the File2.我想用 John 替换 File1 中的 'ABC' 然后应该再次使用原始 File1 并且应该用 Claude 替换 'ABC' 并以类似的方式与第一次迭代合并,直到 File2 的最后一个条目。 So, presently the script is giving the output for only one value 'John' it doesn't take other values from the list.因此,目前脚本仅给出一个值 'John' 的输出,它不会从列表中获取其他值。

Final Output.txt file should be like:最终的 Output.txt 文件应该是这样的:

Name     -> John

Record   -> Exists

Presence -> Existing_John


Name     -> Claude

Record   -> Exists

Presence -> Existing_Claude

.

.

.

.
.


(#till Austin)

Please find me the mistake in my script and Thanks in advance:->请在我的脚本中找到我的错误并提前致谢:->

#!/usr/bin/perl

use strict;

use warnings;

my @blockList   =  load_block_list();

my $rules_file  =  'File1.txt';

my $out_file    =  'out.txt';  

open( my $rules,  '<',  $rules_file  );

open( my $out,    '>',  $out_file  );

my $Orig_line;

my $new_line;

my $key;


foreach my $Element (@blockList) {

    while($Orig_line=<$rules>) {

        chomp($Orig_line);

        $new_line = $Orig_line;

        if($Orig_line =~ m/ABC/) {
            $new_line =~ s/ABC/$Element/;
        }

        print {$out} "$new_line\n";

    }
}

sub load_block_list
{
    my $block_list = "File2.txt";

    open(DAT, $block_list) || die("Could not open file $block_list!");
    my @lines=<DAT>;
    close(DAT);

    my @retVal = ();
    foreach my $line (@lines) {
        $line =~ s/[\r\n]+//g;
        push(@retVal,$line),
    }
    return @retVal;
}

You should read File1.txt before iterating over @blockList .你应该阅读File1.txt迭代之前@blockList Something like this:像这样的东西:

...
my @template = load_template(); 
my @blockList = load_block_list();
...
foreach my $Element (@blockList) {
    foreach my $Orig_line (@template) {
...

load_template should be similar to load_block_list . load_template应该类似于load_block_list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM