How can I run a script recursively in a directory Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How can I run a script recursively in a directory without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am using the following code to decode JPEG-compressed DICOMs.

find ./* -maxdepth 0 -name '*.dcm' -printf 'dcmdjpeg %p %p n' | sh

I run this code inside any folder containing those files.

The problem is that I have a parent folder and a list of sub folders inside this parent folder. Every sub folder contain at least 2000 DICOM (File). How can I apply this code one time inside the parent folder to be executed in all the sub folders at the same time?

Answer

The find command has a switch for that. It’s called -exec.

$ find . -name '*.dcm' -exec dcmdjpeg {} {} ;

This will substitute filenames as they’re found by find into the places where there are {}. So in the above we’ll be doing this for each filename.

dcmdjpeg file1.dcm file1.dcm
dcmdjpeg file2.dcm file2.dcm
...

If there are spaces in your filenames you can use this method:

$ find . -name '*.dcm' -exec dcmdjpeg "{}" "{}" ;

Seeing what’s happening

You can swap out the command dcmdjpeg with the command echo and run the above to see the filenames that’ll get executed.

Example

Say I had this sample data.

$ tree
.
|-- 1
|   |-- 1.dcm
|   |-- 1 space.dcm
|   |-- 2.dcm
|   `-- 3.dcm
|-- 1.dcm
|-- 2
|   |-- 1.dcm
|   |-- 1 space.dcm
|   |-- 2.dcm
|   `-- 3.dcm
|-- 2.dcm
|-- 3
|   |-- 1.dcm
|   |-- 1 space.dcm
|   |-- 2.dcm
|   `-- 3.dcm
`-- 3.dcm

And now when we run the 2nd example that handles spaces in filenames:

$ find . -name '*.dcm' -exec echo "{}" "{}" ;
./2.dcm ./2.dcm
./1/2.dcm ./1/2.dcm
./1/3.dcm ./1/3.dcm
./1/1 space.dcm ./1/1 space.dcm
./1/1.dcm ./1/1.dcm
./3.dcm ./3.dcm
./1.dcm ./1.dcm
./2/2.dcm ./2/2.dcm
./2/3.dcm ./2/3.dcm
./2/1 space.dcm ./2/1 space.dcm
./2/1.dcm ./2/1.dcm
./3/2.dcm ./3/2.dcm
./3/3.dcm ./3/3.dcm
./3/1 space.dcm ./3/1 space.dcm
./3/1.dcm ./3/1.dcm

In the above you can see filenames being echoed out twice per file found.

We are here to answer your question about How can I run a script recursively in a directory - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji