本文介绍了如何使用perl添加和替换线阵列中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过添加一些行并替换一些其他行来编辑文件.我正在尝试使用包含我的文件一行一行的数组,即

I want to edit a file by adding some line and replacing some others.I'm trying to work with an array that contains my file line by line, i.e

    my $output_file_string = `cat $result_dir/$file`;
    my @LINES = split(/\n/, $output_file_string);

我有一个我想在文件中找到的行的哈希表,可以替换它们或在它们之后添加额外的行.我编写了以下代码来识别这些行:

I have a hash table of lines that I want to find in the file, and either replace them or add additional line after them.I wrote the following code to recognize thos lines:

        foreach my $myline (keys %{ $hFiles_added{$file} }) { 
            foreach my $line ( @LINES) {
                  if ($line =~ /\Q$myline\E/) {
                       ### here should be a code for adding a new line after the current line ###
                  }
             }
        }
        #### here should be a code to return the array to the output file ####

我不知道如何添加\替换部分,以及如何将我编辑的文件保存回文件(而不是数组

I can't figure how to do the adding\replacing part, and how to save my edited file back in a file (and not array

谢谢沙哈尔

推荐答案

使用 splice改变@LINES的内容.

使用 openprint@LINES 写回您的文件.

Use open and print to write @LINES back to your file.

如果其他人可能同时在编辑此文件,那么您将需要 flock.

If other people might be editing this file at the same time then you'll need flock.

如果性能对您来说不是那么重要,那么您可以查看 Tie::File.

If performance isn't that important to you then you might look at Tie::File.

对于更复杂的文件处理,您可能需要 seek截断.

For more complicated file handling, you might want seek and truncate.

但这在 Perl 常见问题解答中都有很好的介绍 - 如何更改、删除或插入一行文件,或附加到文件的开头?

But this is all covered well in the Perl FAQ - How do I change, delete, or insert a line in a file, or append to the beginning of a file?

顺便说一句,您的前两行代码可以替换为一行:

By the way, your first two lines of code can be replaced with one:

my @LINES = `cat $result_dir/$file`;

这篇关于如何使用perl添加和替换线阵列中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:59