Perlスクリプトでsedコマンドを実行する

Perlスクリプトでsedコマンドを実行する

次のPerlスクリプトではsedコマンドを呼び出すことはできません。

#!/usr/bin/perl 
my $cmd = ('sed 's/...........//;s/............$//' a_file.txt >> a_newfile.txt');
  system($cmd);

エラーは次のとおりです。

String found where operator expected at ./test.pl line 2, near "s/............$//' a_file.txt >> a_newfile.txt'"
syntax error at ./test.pl line 2, near "'sed 's/...........//"
syntax error at ./test.pl line 2, near "s/............$//' a_file.txt >> a_newfile.txt'"
Execution of ./test.pl aborted due to compilation errors.

<shortname>u********.com</shortname>ファイルから.inを削除し、出力を新しいファイルに保存する必要があります。実行するにはどのようなコマンドが必要ですか?

ベストアンサー1

今はperlより良い結果が得られるという事実を無視し、次は引用の型を使用してsedシェルコマンドラインに渡す引用です。system()q{...}

my $cmd = q{sed 's/...........//;s/............$//' a_file.txt >> a_newfile.txt};

...セクションにアンバランス{/が含まれていないと仮定している}場合は、、...を使用できq@...@ますq[...]q(...)

実際には、コマンドラインがシェルによって解釈されることを望むので(リダイレクトのために)配列ではなくスカラーになりたいです>>(とにかく配列の名前はまさにこれです)。$cmd@cmd$cmd

perlコマンドを単独で実行するにはsed(つまり、シェルを呼び出さずに)次のことを行う必要があります。

my @cmd = ('sed', q{s/...........//;s/............$//}, 'a_file.txt');
system(@cmd);

perlただし、事前に標準出力をリダイレクトする必要があります。良い:

open STDOUT, '>>', 'a_newfile.txt' or die "open: $!"

Perlですべての操作を実行するには、次のようにします。

open my $in, '<', 'a_file.txt' || die "open a_file: $!";
open my $out, '>>', 'a_newfile.txt' || die "open a_newfile: $!";

while (<$in>) {
  s/...........//;s/............$//;
  print $out $_;
}
close $in;
close $out;

おすすめ記事