Operating System - HP-UX
1757083 Members
2098 Online
108858 Solutions
New Discussion юеВ

Perl script to delete older files

 
SOLVED
Go to solution
Krisklan
Advisor

Perl script to delete older files

Hi,

I am new to scripting. I am using the command
find /tmp/histdwn/h0* -type f -mtime +30 -exec rm {} \; to delete files older than 30 days. The command works well on command line on HPUX.

But when I use the same code in a perl script.

#!/opt/OV/contrib/perl/bin/perl
find /tmp/histdwn/h0* -type f -mtime +28 -exec rm {} \;

The error I get is:

Backslash found where operator expected at ./hist.pl line 2, near "} \"
(Missing operator before \?)
syntax error at ./hist.pl line 9, near "} \"
Execution of ./hist.pl aborted due to compilation errors.

Please correct this. Thanks!

6 REPLIES 6
Patrick Wallek
Honored Contributor
Solution

Re: Perl script to delete older files

You are trying to use PERL to run a shell command. That won't work, as you have found.

The easiest way is not to use PERL at all. Create your script as a regular shell script.

# cat my-script
#!/usr/bin/sh
find /tmp/histdwn/h0* -type f -mtime +28 -exec rm {} \;

Now give yourself permissions to run it and you should be fine.
Tim Nelson
Honored Contributor

Re: Perl script to delete older files

Cannot do this the way you are trying.

You can call shell commands from a perl script but not in the direct fashion as you have.

Not sure why you need to use perl to do this but Perl could provide another methods as well. unfortunately I am not a perl guru..

Need to wait until the perl gurus chime in.

Krisklan
Advisor

Re: Perl script to delete older files

Well as i said i m a rookie...:) thanks!
James R. Ferguson
Acclaimed Contributor

Re: Perl script to delete older files

Hi:

Your syntax is fine for a shell but for a Perl script, you should do:

# perl -MFile::Find -le 'find(sub{unlink $File::Find::name if -f $_ && -M _ >= 28},@ARGV)' /path

To match filenames containing "h0", do something like:

perl -MFile::Find -le 'find(sub{print $File::Find::name if -f $_ && -M _ >= 6000 && m{h0}},@ARGV)' /path

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: Perl script to delete older files

>find /tmp/histdwn/h0* -type f -mtime +28 -exec rm {} \;

If you want better performance in find, replace that ";" by a +:
find ... -exec rm {} +
James R. Ferguson
Acclaimed Contributor

Re: Perl script to delete older files

Hi (again):

My second example, adding matching for specific filenames, neglected to change the 'print' to 'unlink' and set the number of days too high. I meant to write:

# To match filenames containing "h0", do something like:

perl -MFile::Find -le 'find(sub{unlink $File::Find::name if -f $_ && -M _ >= 28 && m{h0}},@ARGV)' /path

As you can see, the code can be tested by changing 'unlink' (the system call for 'rm') to 'print'.

Note too, that you can pass multiple '/path' arguments to the script if you want to examine multiple directories.

Regards!

...JRF...