简体   繁体   中英

linux command line recursively check directories for at least 1 file with the same name as the directory

I have a directory containing a large number of directories. Each directory contains some files and in some cases another directory.

parent_directory
  sub_dir_1
    sub_dir_1.txt
    sub_dir_1_1.txt
  sub_dir_2
    sub_dir_2.txt
    sub_dir_2_1.txt
  sub_dir_3
    sub_dir_3.txt
    sub_dir_3_1.txt
  sub_dir_4
    sub_dir_4.txt
    sub_dir_4_1.txt
  sub_dir_5
    sub_dir_5.txt
    sub_dir_5_1.txt

I need to check that each sub_dir contains at least one file with the exact same name. I don' need to check any further down if there are sub directories within the sub_dirs.

I was thinking of using for d in ./*/ ; do (command here); done for d in ./*/ ; do (command here); done for d in ./*/ ; do (command here); done but I dont know how to get access to the sub_dir name inside the for loop

for d in ./*/ ; 
do 
  (if directory does not contain 1 file that is the same name as the directory then echo directory name ); 
done

What is the best way to do this or is there a simpler way?

from the parent directory

find -maxdepth 1 -type d -printf "%f\n" |  
xargs -I {} find {} -maxdepth 1 -type f -name {}.txt

will give you the name/name.txt pair. Compare with the all dir names to find the missing ones.

UPDATE

this might be simpler, instead of scanning you can check whether file exists or not

for f in $(find -maxdepth 1 -type d -printf "%f\n"); 
do if [ ! -e "$f/$f.txt" ]; 
then echo "$f not found"; 
fi; done

Maybe not understand fully, but

find . -print | grep -P '/(.*?)/\1\.txt'

this will print any file which is inside of the same-named directory, eg:

./a/b/b.txt
./a/c/d/d.txt

etc...

Similarly

find . -print | sed -n '/\(.*\)\/\1\.txt/p'

this

find . -print | grep -P '/(.*?)/\1\.'

will list all files regardless of the extension in same-named dirs.

You can craft other regexes following the backreference logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM