-1

I have a simple Perl script that I want to run on a folder full of .txt files.

I read the answers to How do I run a Perl script on multiple input files with the same extension? and did not understand how to implement the answers.

I have have Googled etc. and do not understand the answers on perlmonks.

On my Mac OS terminal I am using

perl myscript.pl input.txt > output.txt

but I don't know how to run it on a folder full of .txt files.

I'd be content with either producing a new set of modified .txt files (one output per input) or editing the files and overwriting the input with the output if that is easier.

Community
  • 1
  • 1
  • Look at the core module File::Find http://perldoc.perl.org/File/Find.html – Neil H Watson Jun 18 '15 at 23:04
  • 1
    How do you want to do this? You can write a wrapper in Perl or in shell that calls your program for each text file in a given directory, or you can modify your Perl program to process many files instead of just one. An intermediate solution is to rewrite `myscript.pl` to accept any number of files and call it with `perl myscript.pl *.txt`. That way it will also still work as it already does. The choice is up to you -- no option is simpler than any other – Borodin Jun 19 '15 at 00:37
  • @NeilHWatson: `File::Find` isn't appropriate for processing all text files in a single directory. Most likely `glob` or possibly `opendir`/`readdir` is the best choice. Or, as I have said, let the shell find the files by using a wildcard parameter – Borodin Jun 19 '15 at 00:40
  • Be more specific. Do you want the equivalent of `perl myscript.pl in1.txt > out1.txt ; perl myscript.pl in2.txt > out2.txt`? Or `perl myscript.pl in1.txt in2.txt > out.txt`? Or `perl myscript.pl file1.txt > file1.txt ; perl myscript.pl file2.txt > file2.txt` (assuming you could do so without destroying the input before it has been processed)? Is there just one folder, or do you want to work recursively in nested subfolders? Does `myscript.pl` accept multiple filename arguments? Why don't you show us what you tried? – 200_success Jun 19 '15 at 03:53
  • Any reason not to use `perl -i.old myscript.pl *.txt`? That assumes that the script doesn't go around explicitly opening files and just uses `while (<>)` or equivalent to read the files and `print` or equivalent to write to the output. The `.old` is the suffix added to the file names; you can omit that and overwrite the originals. – Jonathan Leffler Jun 19 '15 at 04:48

1 Answers1

2

This is more of a command line/bash question than a perl question, from what I understand you want to run the following against multiple files

perl myscript.pl input.txt > output.txt

The easiest way to do this would be to execute the following command from terminal

find . -name "*.txt" -exec sh -c 'perl myscript.pl {} > {}.out' \;

This will get all files that match *.txt, and execute the command between --exec sh -c' and '\;, replacing {} with the name of the file.

harvey
  • 2,945
  • 9
  • 10