开发者

execute command line command from Perl?

HI all,

i need to have this command line command executed from a Perl file:

for file in *.jpg ; do mv $file `echo $file | sed 's/\(.*\.\)jpg/\1jp4/'` ; done

So I added the folders and tried:

system "bash -c 'for file in $mov0to/*.jp4 ; do mv 开发者_StackOverflow社区$file `echo $basedir/internal/0/$file | sed 's/\(.*\.\)jp4/\1jpg/'` ; done'";

But all I get is:

sh: Syntax error: "(" unexpected
No file specified

I am on Kubuntu 10.4

Thanks, Jan


I can think of many better ways of doing this, but ideally you want pure Perl:

use File::Copy qw( move );
opendir DIR, $mov0to or die "Unable to open $mov0to: $!";
foreach my $file ( readdir DIR ) {
    my $out = $file;
    next unless $out =~ s/\.jp4$/.jpg/;
    move "$mov0to/$file", "$basedir/internal/0/$out" or die "Unable to move $mov0to/$file->$basedir/internal/0/$out: $!";
}
closedir DIR;

If you insist on doing the lifting in Bash, you should be doing:

system qq(bash -c 'for file in $mov0to/*.jp4 ; do mv \$file $basedir/internal/0/\${file\/%.jp4\/.jpg} ; done');


All of the variables inside the double quotes will get interpolated, the $file that you're using in the bash for loop in particular. We don't have enough context to know where the other variables ($mov0to and $basedir) come from or what they contain so they might be having the same problems. The double quotes are also eating your backslashes in the sed part.

Andy White is right, you'd have less of a mess if the bash commands were in a separate script.


It's most likely a problem with nested quotes. I would recommend either moving that bash command into its own (bash) script file, or writing the loop/logic directly in Perl code, making simpler system calls if you need to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜