I want to run a Perl script on multiple files, with same name ("Data.txt") but in different directories (eg : 2010_06_09_A/Data.txt, 2010_06_09_B/Data.txt).
I know how to run this perl script on files in the same directory like:
for $i in *.txt
do
perl myscript.pl $i > $i.new
done
But my filenames are same, and they are in different directories. How to go about this? This may be a very basic question, but I am just a beginner!!!
Simply pass full/relative paths with directory name to your perl script. (This is assuming your perl script does not expect the file to be in the current working directory).
## Assuming the following directory structure:
## /abc/xyz/2010_06_09_A
## /abc/xyz/2010_06_09_B
## ...
## /abc/xyz/2010_06_09_Z
cd /abc/xyz
for i in */Data.txt
do
perl myscript.pl $i > $i.new
done
If your perl script needs the file to be current working directory:
cd /abc/xyz
for i in */Data.txt
do
dir=${i%/*}
file=${i##*/}
cd "$dir"
perl myscript.pl ${file} > $i.new
cd -
done
.... <Shell script snipped> ...
a_programmer's shell for loop is far better.
Perl globbing example follows -
You can iterate through all files named "Data.txt" in the Perl program itself, thereby avoiding the shell's for loop.
Example of your Perl script "myscript.pl" -
#!/usr/bin/perl -w
...
while ($file = glob("<your_directory>/*/Data.txt")) {
# Now you have the full path in $file.
# Process it the way you want.
# You can even create and write to "$file.new" thereby
# avoiding the shell's redirection operator.
... your code here
}