SNA
SNA

Reputation: 109

Execute program on Files in subDirectory

I have following architecture of files in a directory.

  Directory
     /A/abc.xyz
     /B/abc.xyz
     /C/abc.xyz
     /D/abc.xyz
     /E/abc.xyz

I want to execute a program on acb.xyz in each SubDirectory. Save Output files in different directory i.e. Directory/processed with the name of SubDirectory appended in the name of output files. Can it be written in following way? Need corrections.

for i in `ls "Directory/"`
do
  program.pl $i/abc.xyz > processed/$i-abc.xyz
done

Upvotes: 0

Views: 269

Answers (1)

John Kugelman
John Kugelman

Reputation: 362157

for dir in Directory/*; do
    program.pl "$dir/abc.xyz" > "processed/${dir##*/}-abc.xyz"
done

The ${dir##*/} part strips the leading directory names from $dir, so Directory/A becomes just A. I added quotes to ensure directory names with whitespace don't cause issue (a good habit, even if you know there are no spaces).

As an alternative to the string munging you could simplify this if you first change directory:

cd Directory

for dir in *; do
    program.pl "$dir/abc.xyz" > "processed/$dir-abc.xyz"
done

Upvotes: 2

Related Questions