0

I have a data directory has has three sub-directories and each sub-directory has three different sub-directories. And I need to read two different files from the last sub-directory. How can I accomplish this?

I tried this using the below code and I am not able to navigate through all the sub-directories.

cd $datadir

for dirs in *;

do

cd $dirs


    for folders in *; 

        do 

        echo $folders; 


        file1=$(find "$folders" -name '*regADNI.nii.gz');
        file2=$(find "$folders" -name '*0.25mm-Crop.nii.gz');

        echo $file1
        echo $file2 

        fname=$(echo "$file1" | sed 's|\(.*\)/.*|\1|');
        #echo $fname

        echo "***************"

    done

cd .
pwd

Following is the folder organization

enter image description here

Can anyone help me with this?

Thanks Anandh.

Parsa Mousavi
  • 3,305
  • 16
  • 37

1 Answers1

0

This is a bit easier if you don't cd around while trying to do this. It makes sense to try, but it just gets a bit messy when you need to manage where you are in a script; moving up/down directories all the time.

I'd recommend instead building up the file paths that you need to search, and then using find on those directories without moving. For example:


for topDir in $(ls -d ./a*/); do
    for subDir in $(ls -d $topDir*/); do
        for leafDir in $(ls -d $subDir*/); do
            echo "Dir  : $leafDir"
            file1=$(find "$leafDir" -name '1.gz')
            file2=$(find "$leafDir" -name '2.gz')
            echo "Files:" $file1 $file2
        done
    done
done

The script above does 3 loops, building up the directories to search from listings of only directories in each previous directly. Executed on the directory structure below:

justin@mal:~$ tree a
a
├── a
│   ├── a
│   │   ├── 1.gz
│   │   └── 2.gz
│   ├── b
│   │   ├── 1.gz
│   │   └── 2.gz
│   └── c
├── b
│   ├── a
│   │   ├── 1.gz
│   │   └── 2.gz
│   ├── b
│   │   └── 1.gz
│   └── c
│       ├── 1.gz
│       └── 2.gz
└── c
    ├── a
    ├── b
    └── c
        ├── 1.gz
        └── 2.gz

12 directories, 11 files

gives

justin@mal:~$ bash script 
Dir  : ./a/a/a/
Files: ./a/a/a/1.gz ./a/a/a/2.gz
Dir  : ./a/a/b/
Files: ./a/a/b/1.gz ./a/a/b/2.gz
Dir  : ./a/a/c/
Files:
Dir  : ./a/b/a/
Files: ./a/b/a/1.gz ./a/b/a/2.gz
Dir  : ./a/b/b/
Files: ./a/b/b/1.gz
Dir  : ./a/b/c/
Files: ./a/b/c/1.gz ./a/b/c/2.gz
Dir  : ./a/c/a/
Files:
Dir  : ./a/c/b/
Files:
Dir  : ./a/c/c/
Files: ./a/c/c/1.gz ./a/c/c/2.gz

You should be able to adapt this to your specific top-level directory name and file name structures without too much trouble (switch out the top a folder and the file1, file2 names). Hope this helps.

justincely
  • 123
  • 1
  • 6