如何在 Perl 文件的顶部和底部添加行? [英] How do I add lines to the top and bottom of a file in Perl?

查看:35
本文介绍了如何在 Perl 文件的顶部和底部添加行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文件的顶部和底部添加一行.我可以按照以下方式进行.

I want to add a line to top and bottom of the file. I can do it following way.

open (DATA, "</usr/old") || die "cant open old\n"; #file to which line has to be added

my @body=<DATA>;
close(DATA);

open (FILE, ">/usr/new") || die "cant open new\n"; #file after stuff has been added

print FILE "9   431";

print FILE "\n";

my $body=@body;

for (my $i=0; $i<$body;$i++){

    print FILE "$body[$i]";#not using for loop leads to addition of spaces in new file
}

print FILE "(3,((((1,4),(7,6)),(2,8)),5),9)";

由于我要运行大量文件,因此此过程将非常耗时.Perl 是否具有用于在文件顶部和底部添加行的特定功能?

Since I running for a large set of file this process will be time consuming. Does Perl has any specific functionality which used to add lines at top and bottom of a file?

推荐答案

来自 perlfaq5如何更改、删除或在文件中插入一行,或附加到文件的开头一个文件?

如何更改、删除或在文件中插入一行,或附加到文件的开头?

How do I change, delete, or insert a line in a file, or append to the beginning of a file?

(由 Brian d foy 提供)

(contributed by brian d foy)

在文本文件中插入、更改或删除行的基本思想包括读取和打印文件到您要更改的点,进行更改,然后读取和打印文件的其余部分.Perl 不提供对行的随机访问(特别是因为记录输入分隔符 $/是可变的),尽管诸如 Tie::File 之类的模块可以伪造它.

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.

要将行添加到开头,请在进入打印现有行的循环之前打印这些行.

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;

要更改现有行,请插入代码以修改 while 循环内的行.在这种情况下,代码会找到perl"的所有小写版本并将它们大写.每一行都会发生这种情况,所以请确保您应该在每一行都这样做!

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 $_;
    }

要跳过行,请使用循环控件.本示例中的下一个跳过注释行,最后一个在遇到 ENDDATA 时停止所有处理.

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 $_;
    }

通过使用 next 跳过您不想在输出中显示的行,执行相同的操作以删除特定行.此示例每五行跳过一次:

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;

诸如 File::Slurp 和 Tie::File 之类的模块也可以提供帮助.但是,如果可以,请避免一次读取整个文件.在进程完成之前,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 one-liners 就地修改文件.以下将 inFile.txt 中的所有Fred"更改为Barney",并使用新内容覆盖文件.使用 -p 开关,Perl 会在您使用 -e 指定的代码周围环绕一个 while 循环,而 -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天全站免登陆