如何在 Perl 中向文件的顶部和底部添加行?

发布于 2024-07-30 08:06:18 字数 568 浏览 4 评论 0原文

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

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 是否有用于在文件顶部和底部添加行的特定功能?

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)";

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

深空失忆 2024-08-06 08:06:19

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


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

(由 brian d foy 贡献)

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

执行这些任务的 Perl 程序采用的基本形式是打开文件、打印其行,然后关闭文件:

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;

在该基本形式中,添加插入、更改或删除行所需的部分。

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

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”的所有小写版本并将它们转为大写。 每行都会发生这种情况,因此请确保您应该在每行上执行此操作!

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;

要仅更改特定行,输入行号 $. 很有用。 首先阅读并打印直到您要更改的行。 接下来,读取要更改的单行,更改它,然后打印它。 之后,阅读其余行并打印它们:

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 时会停止所有处理。

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

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

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

如果出于某种奇怪的原因,您确实想立即查看整个文件而不是逐行处理,则可以将其吞入其中(只要您可以将整个文件放入内存!) :

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 不会将内存返还给操作系统。

您还可以使用 Perl 语句就地修改文件。 以下命令将 inFile.txt 中的所有“Fred”更改为“Barney”,并用新内容覆盖该文件。 使用 -p 开关,Perl 会在您使用 -e 指定的代码周围包装一个 while 循环,并且 -i 打开就地编辑。 当前行位于 $ 中。 使用 -p,Perl 在循环结束时自动打印 $ 的值。 有关详细信息,请参阅 perlrun。

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

要备份 inFile.txt,请给 -ia 文件扩展名添加:

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

要仅更改第五行,可以添加一个测试检查 $.,输入行号,然后仅在测试通过时执行操作:

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

添加在特定行之前,您可以在 Perl 打印 $_ 之前添加一行(或多行!):

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

在循环的末尾:

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

您甚至可以在文件的开头添加一行,因为当前行打印 文件中已存在一行后,请使用 -n 开关。 它就像 -p 一样,只不过它不会在循环末尾打印 $_ ,因此您必须自己执行此操作。 在这种情况下,首先打印 $_,然后打印要添加的行。

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

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

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

    ... or ...

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

From perlfaq5's answer to How do I change, delete, or insert a line in a file, or append to the beginning of a file?


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

(contributed by brian d foy)

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.

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;

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

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;

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.

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

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

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

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
抚你发端 2024-08-06 08:06:19

使用 Tie::File ,它可以让您通过Perl 数组。 它带有标准发行版。

Example from documentation:

use Tie::File;

tie @array, 'Tie::File', filename or die ...;
$array[13] = 'blah';     # line 13 of the file is now 'blah'
print $array[42];        # display line 42 of the file

$n_recs = @array;        # how many records are in the file?
$#array -= 2;            # chop two records off the end

for (@array) {
    s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
}

# These are just like regular push, pop, unshift, shift, and splice
# Except that they modify the file in the way you would expect
push @array, new recs...;
my $r1 = pop @array;
unshift @array, new recs...;
my $r2 = shift @array;
@old_recs = splice @array, 3, 7, new recs...;

untie @array;            # all finished

Use Tie::File which gives you access to the lines of a disk file via a Perl array. It comes with standard distribution.

Example from documentation:

use Tie::File;

tie @array, 'Tie::File', filename or die ...;
$array[13] = 'blah';     # line 13 of the file is now 'blah'
print $array[42];        # display line 42 of the file

$n_recs = @array;        # how many records are in the file?
$#array -= 2;            # chop two records off the end

for (@array) {
    s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
}

# These are just like regular push, pop, unshift, shift, and splice
# Except that they modify the file in the way you would expect
push @array, new recs...;
my $r1 = pop @array;
unshift @array, new recs...;
my $r2 = shift @array;
@old_recs = splice @array, 3, 7, new recs...;

untie @array;            # all finished
抱猫软卧 2024-08-06 08:06:19

给出的三个答案使这种非常糟糕的做法长期存在:

open(FILE,"<file") or die "cannot open";

不仅如此,代码也被破坏了,因为您打开文件不是为了写入而是为了读取。

当打开失败时,您可以告诉用户失败的原因。 请养成包含$的习惯! 在错误消息中。 另外,使用 open 的三个参数形式将模式与名称分开:(

my $path="file";
open my($fh), '>', $path or die "$path: $!";

这不能回答您的问题,但我将其作为答案而不是注释以增加强调,以便我可以回顾一下,因为它是一个相当长的喷涌。)

Three answers have been given that perpetuate the very bad practice of:

open(FILE,"<file") or die "cannot open";

Not only that, the code is broken since you are not opening the file for writing but for reading.

When an open fails, you can tell the user why it failed. Please get in the habit of including $! in the error message. Also, use the three argument form of open to separate the mode from the name:

my $path="file";
open my($fh), '>', $path or die "$path: $!";

(This does not answer your question, but I'm making it an answer rather than a comment for added emphasis and so that I can review it as it is a rather lengthy spewing forth.)

梦初启 2024-08-06 08:06:19

Perl 无法在文件开头插入,因为很少有操作系统允许这样做。 您需要此处类型的重写操作。

该代码可能遇到的一个问题是,真正的大文件无法容纳在您的地址空间中。

通过读取整个文件然后将其写出,您可能会遇到内存问题。 我会做的是:

  • 重命名当前文件,
  • 用您想要在开始时插入的内容重新创建它,
  • 将重命名的文件大块(不一定是行)复制到新文件的末尾,
  • 添加新文件最后一点。

这将是快速且节省内存的。

当然,如果您的文件足够小以适合内存,请坚持使用您拥有的文件。 已经足够好了。

更新

似乎有足够多的人误解了我提倡的 shell 脚本,而我认为我已经把它搞清楚了。 您可以在本机 Perl 中执行上述所有操作。

但您可能需要考虑是否有必要使用 Perl。 像这样的 shell 命令也

( echo '9   431';cat /usr/old;echo '(3,((((1,4),(7,6)),(2,8)),5),9)' ) >/usr/new

能达到同样的目的(而且可能同样快)。

当然,如果您需要 Perl,那么请忽略此更新,将其视为老人的胡言乱语:-)

Perl can't insert at the beginning of a file because few operating systems allow that. You need a rewrite operation of the type you have here.

One possible problem you may have with that code is with truly large files that can't fit in your address space.

By reading the entire file in then writing it out, you may run into memory problems. What I would have done would be to:

  • rename the current file
  • re-create it with the stuff you want inserted at the start,
  • copy the renamed file in large chunks (not necessarily lines) to the end of the new file,
  • add the new bit at the end.

This will be fast and memory-efficient.

Of course, if your files are small enough to fit in memory, stick with what you have. It's good enough.

Update:

Enough people seem to be under the misapprehension that I'm advocating a shell script that I thought I'd set it straight. You can do all the things above from within native Perl.

But you may want to consider if it's necessary to use Perl. A shell command like:

( echo '9   431';cat /usr/old;echo '(3,((((1,4),(7,6)),(2,8)),5),9)' ) >/usr/new

will do the trick just as well (and probably just as fast).

Of course, if you need Perl, then just ignore this update as the ramblings of an old man :-)

居里长安 2024-08-06 08:06:19

有很多方法可以做到这一点,例如使用 @Pax 提到的简单 shell 脚本。 您还可以用 join() 替换数组和循环:

open(DATA, "</usr/old") || die "cant open old\n"; #file to which line has to be added
my $body=join("", <DATA>);
open (FILE, ">/usr/new") || die "cant open new\n"; #file after stuff has been added
print FILE "9   431\n";
print(FILE $body);
print FILE "(3,((((1,4),(7,6)),(2,8)),5),9)";
close(FILE);

There's many ways you can do it, for example with a simple shell script the way @Pax mentioned. You can also replace your array and loop with a join():

open(DATA, "</usr/old") || die "cant open old\n"; #file to which line has to be added
my $body=join("", <DATA>);
open (FILE, ">/usr/new") || die "cant open new\n"; #file after stuff has been added
print FILE "9   431\n";
print(FILE $body);
print FILE "(3,((((1,4),(7,6)),(2,8)),5),9)";
close(FILE);
凉墨 2024-08-06 08:06:19

我对 Ghostdog74 的修改是文件句柄应该在打印语句中,并且文件应该在第二个打印语句之后关闭。

    open(FILE, ">", "file") or die "cannot open $file: $!"; 
    print FILE "add line to top";
    while (<FILE>) { print $_;}
    print FILE "add line to bottom";
    close(FILE);

My modification to ghostdog74 is that file handle should in the print statements and the file should be closed after the second print statement.

    open(FILE, ">", "file") or die "cannot open $file: $!"; 
    print FILE "add line to top";
    while (<FILE>) { print $_;}
    print FILE "add line to bottom";
    close(FILE);
情泪▽动烟 2024-08-06 08:06:19

你可以

open(FILE,">", $file) or die "cannot open $file: $!";
print FILE "add line to top\n";
while (<FILE>) { print $_ ."\n";}
close(FILE);
print FILE "add line to bottom\n";

在命令行上执行此操作

perl myscript.pl > newfile

you can do this

open(FILE,">", $file) or die "cannot open $file: $!";
print FILE "add line to top\n";
while (<FILE>) { print $_ ."\n";}
close(FILE);
print FILE "add line to bottom\n";

on command line

perl myscript.pl > newfile
梅窗月明清似水 2024-08-06 08:06:19

正如帕克斯所说,没有内置的方法可以做到这一点。 但如果您想在 shell 中使用单行 perl 命令来完成此操作,您可以使用:

perl -ple 'print "Top line" if $. == 1; if (eof) { print "$_\nBottom line";  exit; }' yourfile.txt > newfile.txt

As Pax says, there is no built-in way to do this. But if you want to do it with a single line perl command from your shell, you can use:

perl -ple 'print "Top line" if $. == 1; if (eof) { print "$_\nBottom line";  exit; }' yourfile.txt > newfile.txt
幽蝶幻影 2024-08-06 08:06:19

我不太会说 Perl,但也许这适用于某些情况:

perl -0777 -pi -e 's/^/MY TEXT TO PREPEND/' myfile.txt

也就是说,以段落模式(一行)打开文件,并用新文本替换该行的开头,进行就地重写。

对于许多大文件来说可能效率不高。

I don't really speak Perl, but perhaps this works for some situations:

perl -0777 -pi -e 's/^/MY TEXT TO PREPEND/' myfile.txt

That is, open the file in paragraph mode (one line), and replace the start of that line with your new text, doing an in-place rewrite.

Probably not efficient for many large files.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文