如何更换线用Perl文件的中间? [英] How do I replace lines in the middle of a file with Perl?

查看:214
本文介绍了如何更换线用Perl文件的中间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开追加模式的文件。我需要更换线路2,3和4的文件中,以后我需要在文件的末尾添加新的数据。

I am opening the file in append mode. I need to replace lines 2,3, and 4 in the file, and later I need to add the new data at the end of the file.

推荐答案

我觉得这是我要重新发布StackOverflow的最常见问题的答案。该 perlfaq5 有答案<一个href=\"http://learn.perl.org/faq/perlfaq5.html#How-do-I-change-delete-or-insert-a-line-in-a-file-or-append-to-the-beginning-of-a-file\"相对=nofollow>如何更改,删除或插入在文件中的行,或附加到文件的开始?。

I think this is the FAQ answer that I've reposted to Stackoverflow the most. The perlfaq5 has the answer to How do I change, delete, or insert a line in a file, or append to the beginning of a file?.

忘记追加模式的东西。这只是打算让您的生活困难。

Forget about the append mode stuff. That's just going to make your life harder.

插入,更改或删除从一个文本文件中的行的基本思想包括阅读和打印文件要进行修改的位置,进行更改,然后阅读和打印文件的其余部分。 Perl不提供对线路随机访问(特别是因为记录输入分隔符, $ / ,是可变的),虽然模块等的领带::文件可以伪造的。

The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Perl doesn't provide random access to lines (especially since the record input separator, $/, is mutable), although modules such as Tie::File can fake it.

一个Perl程序来完成这些任务需要打开一个文件,打印其行,然后关闭该文件的基本形式:

A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file:

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

while( <$in> )
    {
    print $out $_;
    }

close $out;

在这一基本形式,添加你需要插入,更改或删除线的部分。

Within that basic form, add the parts that you need to insert, change, or delete lines.

要prePEND线开始,你输入打印现有生产线循环之前打印这些行。

To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines.

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

print $out "# Add this line to the top\n"; # <--- HERE'S THE MAGIC

while( <$in> )
    {
    print $out $_;
    }

close $out;

要改变现有的生产线,将code修改while循环中的行。在这种情况下,code发现perl的所有小写版本,并uppercases他们。该发生的每一行,所以一定是你应该做的是在每行了!

To change existing lines, insert the code to modify the lines inside the while loop. In this case, the code finds all lowercased versions of "perl" and uppercases them. The happens for every line, so be sure that you're supposed to do that on every line!

open my $in,  '<',  $file      or die "Can't read old file: $!";
open my $out, '>', "$file.new" or die "Can't write new file: $!";

print $out "# Add this line to the top\n";

while( <$in> )
    {
    s/\b(perl)\b/Perl/g;
    print $out $_;
    }

close $out;

要改变只有一个特定的行,的输入行号, $ ,是非常有用的。首先阅读和打印排队到要改变的人。接下来,读你想改变,改变单一的线,并打印。此后,读出的行的其余部分和打印这些

To change only a particular line, the input line number, $., is useful. First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. After that, read the rest of the lines and print those:

while( <$in> )   # print the lines before the change
    {
    print $out $_;
    last if $. == 4; # line number before change
    }

my $line = <$in>;
$line =~ s/\b(perl)\b/Perl/g;
print $out $line;

while( <$in> )   # print the rest of the lines
    {
    print $out $_;
    }

要跳过的行,使用循环控制。在这个例子中的下一个跳过注释行,一旦它遇到的最后一个停止所有处理要么 __结束__ __ DATA __

To skip lines, use the looping controls. The next in this example skips comment lines, and the last stops all processing once it encounters either __END__ or __DATA__.

while( <$in> )
    {
    next if /^\s+#/;             # skip comment lines
    last if /^__(END|DATA)__$/;  # stop at end of code marker
    print $out $_;
    }

做同样的事情用旁边跳过你不想在输出中显示出来的线条删除特定行。这个例子每跳过第五行:

Do the same sort of thing to delete a particular line by using next to skip the lines you don't want to show up in the output. This example skips every fifth line:

while( <$in> )
    {
    next unless $. % 5;
    print $out $_;
    }

如果,出于某种奇怪的原因,你真的想看到整个文件的一次,而不是加工生产线由行,你可以在(只要你能适应在内存中的整个事情!)啜食吧:

If, for some odd reason, you really want to see the whole file at once rather than processing line-by-line, you can slurp it in (as long as you can fit the whole thing in memory!):

open my $in,  '<',  $file      or die "Can't read old file: $!"
open my $out, '>', "$file.new" or die "Can't write new file: $!";

my @lines = do { local $/; <$in> }; # slurp!

    # do your magic here

print $out @lines;

模块,如档案::嘟嘟地喝并的领带::文件可以与帮助了。如果你可以,但是,避免读取整个文件一次。 Perl会不会给内存返回给操作系统,直到过程完成。

Modules such as File::Slurp and Tie::File can help with that too. If you can, however, avoid reading the entire file at once. Perl won't give that memory back to the operating system until the process finishes.

您也可以使用Perl单行修改就地文件。以下更改所有的弗雷德的到的'巴尼'中的 inFile.txt 的,覆盖新内容的文件。随着 -p 开关,Perl的环绕在code while循环您 -e 指定,并 -i 打开就地编辑。当前行是在 $ _ 。随着 -p ,Perl的自动打印 $ _ 在循环结束时的价值。请参见 perlrun 了解更多详情。

You can also use Perl one-liners to modify a file in-place. The following changes all 'Fred' to 'Barney' in inFile.txt, overwriting the file with the new contents. With the -p switch, Perl wraps a while loop around the code you specify with -e, and -i turns on in-place editing. The current line is in $_. With -p, Perl automatically prints the value of $_ at the end of the loop. See perlrun for more details.

perl -pi -e 's/Fred/Barney/' inFile.txt

要做出inFile.txt的备份,给 -i 文件扩展名补充:

To make a backup of inFile.txt, give -i a file extension to add:

perl -pi.bak -e 's/Fred/Barney/' inFile.txt

要改变只有第五行,可以添加一个测试检查 $ ,输入行号,那么只有执行该操作的时候测试通过了:

To change only the fifth line, you can add a test checking $., the input line number, then only perform the operation when the test passes:

perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt

要Perl的打印之前一定行前加行,你可以添加一行 $ _ (或行!):

To add lines before a certain line, you can add a line (or lines!) before Perl prints $_:

perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt

您甚至可以在循环的末尾添加一行到文件的开头,因为当前行打印:

You can even add a line to the beginning of a file, since the current line prints at the end of the loop:

perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt

要插入一个已经在文件后一条线,使用 -n 开关。这就像 -p 但它不会在循环结束打印 $ _ ,所以你必须自己做。在这种情况下,打印 $ _ ,然后再打印您要添加的行。

To insert a line after one already in the file, use the -n switch. It's just like -p except that it doesn't print $_ at the end of the loop, so you have to do that yourself. In this case, print $_ first, then print the line that you want to add.

perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt

要删除行,只打印你想要的。

To delete lines, only print the ones that you want.

perl -ni -e 'print unless /d/' inFile.txt

    ... or ...

perl -pi -e 'next unless /d/' inFile.txt

这篇关于如何更换线用Perl文件的中间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆