如何在文件中更改,删除或插入一行,或者追加到Perl中文件的开头? [英] How do I change, delete, or insert a line in a file, or append to the beginning of a file in Perl?

查看:2404
本文介绍了如何在文件中更改,删除或插入一行,或者追加到Perl中文件的开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们一直在问这个问题,并且使用与 perlfaq5 相同的答案,我一直在回答这个问题。现在我们可以指向Stackoverflow。

解决方案

perlfaq5



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



一个Perl程序做这些任务是打开一个文件的基本形式,打印它的行,然后关闭文件:

 打开我的$, '<',$ file or die无法读取旧文件:$!; 
打开我的$ out,'>',$ file.new或死不能写新文件:$!;

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

关闭$ out;

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

要在开始之前添加行,请在输入打印现有行的循环之前打印这些行。

 打开我的$ in,'<',$ file或die无法读取旧文件:$! 
打开我的$ out,'>',$ file.new或死不能写新文件:$!;

print $ out#将此行添加到top\\\
; #< ---这里的魔法

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

关闭$ out;

要更改现有行,请插入代码以修改 循环。在这种情况下,代码会找到所有较低版本的perl,并将它们加载到其中。每一行都会发生,所以要确保你应该在每一行上这样做!

 打开我的$, '<',$ file or die无法读取旧文件:$!; 
打开我的$ out,'>',$ file.new或死不能写新文件:$!;

print $ out#将此行添加到top\\\
;

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

关闭$ out;

要仅更改特定行,输入行号 $。,是有用的。首先阅读并打印要更改的行。接下来,阅读要更改的单行,更改它并打印。之后,阅读其余的行并打印:

  while(< $ in>)#打印前面的行更改
{
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 $ out $ _;
}

要跳过行,请使用循环控件。此示例中的下一个将跳过注释行,而最后一次停止所有处理,只要遇到 __ END __ __ DATA __

  while (< $ in>)
{
next if / ^ \s +#/; #跳过注释行
last if / ^ __(END | DATA)__ $ /; #停在代码标记结束
print $ out $ _;
}

使用<$ c删除特定行也是一样的事情$ c> next 跳过您不想在输出中显示的行。这个例子跳过每五行:

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

如果由于某种奇怪的原因,您真的想看到整个文件一次,而不是逐行处理,你可以在它(只要你可以适应整个事情在记忆中!):呃,

 打开我的$ in,'<',$ file或die无法读取旧文件:$! 
打开我的$ out,'>',$ file.new或死不能写新文件:$!;

我的@lines = do {local $ /; < $&中GT; }; #slurp!

#在这里做你的魔法

打印$ out @lines;

模块如 File :: Slurp Tie ::文件也可以帮助。但是,如果可以避免一次读取整个文件。 Perl将不会将该内存恢复到操作系统,直到进程完成为止。



您还可以使用Perl one-liners在现场修改文件。以下将所有Fred更改为codeinFile.txt 中的Barney,用新内容覆盖文件。使用 -p 开关,Perl会绕着您指定的代码循环循环, e 和 -i 打开就地编辑。当前行位于 $ _ 中。使用 -p ,Perl将在循环结束时自动打印 $ _ 的值。有关详细信息,请参阅 perlrun

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

要在File.txt 中备份,请向 -i 添加文件扩展名:

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

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

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

要在某行之前添加行,您可以添加一行或线条!)之前Perl打印 $ _

  perl -pi -e'print放在第三行之前\如果$。 == 3'inFile.txt 

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

  perl -pi -e'print放在第一行之前如果$。 == 1'inFile.txt 

要在文件中已经插入一行,请使用 -n 开关。它就像 -p ,除了它在循环结束时不打印 $ _ ,所以你有自己去做在这种情况下,首先打印 $ _ ,然后打印要添加的行。

  perl -ni -e'print;打印放在第五行之后如果$。 == 5'inFile.txt 

要删除行,只打印所需的行。 p>

  perl -ni -e'打印,除非/ d /'inFile.txt 

...或。 ..

perl -pi -e'next除非/ d /'inFile.txt


People keep asking this question and I keep answering it with the same answer from perlfaq5. Now it's something we can point to on Stackoverflow.

解决方案

From perlfaq5:

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. It 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

这篇关于如何在文件中更改,删除或插入一行,或者追加到Perl中文件的开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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