Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

handle special character in filename

by Anonymous Monk
on Oct 17, 2012 at 10:53 UTC ( #999517=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I have a perl script and I do search and replace using sed inside the script. If the file name is having special character, script fails with error as "sh: -c: line 0: syntax error near unexpected token `('". Could you please help me to fix this issue.
$file=extrac(app).jpg $org=app $rep=fedora $cmd = "sed -i s/$org/$rep/g $file"; system($cmd);


Replies are listed 'Best First'.
Re: handle special character in filename
by moritz (Cardinal) on Oct 17, 2012 at 10:59 UTC
      I did not get it.Could you please explain how to modify in this sed command.

        system("sed","-i","s/$org/$rep/g", $file);

        By the way, you can use Tie::File and \Q..\E constructs inside native Perl regexps (instead of sed), thus not having to run sed (which costs you another fork() and some rename operations) and being able to replace any strings containing any special sharacters.

        Sorry if my advice was wrong.

      The list form may work in this case, but I doubt that it will if the special character is a space. I have been unable to truly solve a similiar problem where system does not correctly parse a command that includes filenames that contain spaces.



        I have test system $command,@params with sed and a file with space in its filename, and it works (at least in Debian)

        $ echo "pa" > "a b" $ cat p system ("sed","s,a,o,","a b"); $ perl p po
Re: handle special character in filename
by choroba (Bishop) on Oct 17, 2012 at 10:58 UTC
    This is not a Perl question (what language is your script in, by the way?). In shell, file names with special character must be quoted.
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      This is perl script only. Used a sed command inside the perl script. I just copied and pasted the lines which were having issues.
      $file="extrac(app).jpg"; $org=app'; $rep=fedora;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://999517]
Approved by betterworld
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2018-05-25 11:24 GMT
Find Nodes?
    Voting Booth?