脚本内的Perl sed文件



假设我需要删除文件第一行中的每个空格(或任何其他sed内容,无关紧要)。如果我从终端执行,这将工作:

perl -i -pe 's/ //g if $. == 1' file.txt

但是我需要在perl脚本中做这个。我可以使用system做到这一点,但我发现不认为这是正确的解决方案,使系统调用perl从perl脚本内。

有没有办法使这个工作很好和没有显式的文件打开?
附注:当然,有一些模块可以做到这一点,但我对核心功能更感兴趣。 P.P.S.我需要在文件

上执行这些操作

您可以显式地编写-p命令行开关的功能,

sub pe {
  my $f = shift;
  local @ARGV = @_;
  local $^I = ""; # -i command line switch
  local $_;
  while (<>) {
    $f->();
    print;
    close ARGV if eof; # reset $. for each file
  }
}
pe(
  sub { s/ //g if $. == 1 },
  "file.txt"
);

可以了

#!/usr/bin/perl
use strict;
use warnings;
my $line = <>;
$line =~ s/ //g;
print $line, <>;
编辑:

这是本地编辑版本。

use strict;
use warnings;
{
    local $^I = '.bak';
    while (<>) {
        s/ //g if $. == 1;
        print;
    }
}

这是你想要的吗?

$ # Setup
$ for number in {1..9}
> do
>     {
>     echo words are separated by spaces
>     echo lines follow each other
>     echo until the end
>     } > file.$number
> done
$ cat file.1
words are separated by spaces
lines follow each other
until the end
# Change the files
$ perl -i.bak -e 'while (<>) { s/ //g if $. == 1; print; } continue { $. = 0 if eof; }' file.?
# Demonstrate that all files are affected
$ cat file.1
wordsareseparatedbyspaces
lines follow each other
until the end
$ cat file.8
wordsareseparatedbyspaces
lines follow each other
until the end
$ rm -f file.? file.?.bak
$

很容易编写只影响第一个文件的第一行的代码(continue块通过在命令行中每个文件末尾重置$.来处理这一点)。

使用神奇的<>操作符遍历文件并更改第一行

你可以试试:

while(my $fh=<>){
$fh=~ s/ //g if($.==1);
print "$fh";
}

最新更新