2

context: I'm a beginner in Perl and struggling, please be patient, thanks.

the question: there is a one-liner that seems to do the job I want (in a cygwin console it does fine on my test file). So now I would need to turn it into a script, but I can't manage that unfortunately.

The one-liner in question is provided in the answer by Aki here Delete lines in perl

perl -ne 'print unless /HELLO/../GOODBYE/' <file_name>

Namely I would like to have a script that opens my file "test.dat" and removes the lines between some strings HELLO and GOODBYE. Here is what I tried and which fails (the path is fine for cygwin):

#!/bin/perl
use strict;
use warnings;

open (THEFILE, "+<test.dat") || die "error opening";
my $line;
while ($line =<THEFILE>){
next if /hello/../goodbye/;
print THEFILE $line;
}
close (THEFILE);

Many thanks in advance!

4

1 回答 1

2

您的单行相当于以下

while (<>) {
    print unless /HELLO/../GOODBYE/;
}

你的代码做了一些完全不同的事情。您不应该尝试读取和写入同一个文件句柄,这通常不会按照您的想法进行。当您想快速编辑文件时,可以使用-i“就地编辑”开关:

perl -ni -e 'print unless /HELLO/../GOODBYE/' file

请注意,对文件的更改是不可逆的,因此您应该进行备份。您可以使用该开关的备份选项,例如-i.bak,但请注意它并非完美无缺,因为两次运行相同的命令仍会覆盖您的备份(通过两次保存到相同的文件名)。

IMO,最简单和最安全的方法是简单地使用 shell 重定向

perl script.pl file.txt > newfile.txt

在使用我在顶部显示的脚本文件时。

于 2013-09-21T16:05:39.887 回答