4

I am unable to invoke the sed command from the perl script as below:

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

Below is the error:

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.

I need to remove the <shortname>u********.com</shortname> in the file and save the output in a new file. Which commands do I need to run?

  • 7
    Why do you want to run sed from perl? – Satō Katsura Oct 30 '17 at 16:06
  • 1
    You're trying to embed single quotes in a single quoted string, but you haven't done anything to escape them. – glenn jackman Oct 30 '17 at 16:09
15

Ignoring for now the fact that perl can do better anything that sed can do, here to quote the shell command line to pass to system(), best would be to use the q{...} type of quotes:

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

(assuming the ... part doesn't contain unbalanced {/}, if it does, you can use q@...@, q[...], q(...)...).

Because you do want a shell to interpret that command line (for the >> redirection), you want $cmd to be a scalar, not array (anyway arrays are named @cmd, not $cmd).

For perl to run the sed command by itself, that is without invoking a shell, you'd do:

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

But then, you'd need to do the stdout redirection in perl beforehand. Like:

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

To do the whole thing in perl instead:

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.