1

Actually, I have a folder which contains several sub folders with lots of images in each.

I am trying to gather all the names of the files in each sub folder in a text file (filesNames.txt) in that sub folder in the form of:

Absolute/path/to/each/file/filename

So, I wrote an script in the parent folder:

#!/bin/sh

for dir in "$PWD"/*/; do
arr=( "$dir"* )
cd "$dir"
printf "%s 1\n" "$PWD/${arr[@]##*/}" > "$dir"filesNames.txt
cd ..
done

My problem is that:

I have the absolute address just for the first file in each sub folder. For the rest there is only filenames without absolute address:

 /run/media/parent_folder/subfolder/filename1.png
 filename2.png
 filename3.png
 ...

I think it is related to $PWD variable which I iterate over it just once for each sub folder. How can I change the script in a suitable form?

Thanks in advance.

  • @don_crissti To have sub folder names in the printed absolute path of each file. – Ali May 23 '16 at 18:16
  • Why didn't you say you need full paths ? Just replace ${arr[@]##*/}" in my answer here with "${arr[@]}" – don_crissti May 23 '16 at 18:17
  • @don_crissti You're right, sorry. – Ali May 23 '16 at 18:26
2

Single find command will output all the files with absolute path

find $(pwd) -type f
1

And if you want to do that using pure shell script and dont want to use find, try this little one:

#!/bin/bash
#Simple bash recursive loop search - Luciano A. Martini =) 
nextdir(){
for f in *; do 
   if [ -d "$f" ] && [ ! -L "$f" ]; then
        #echo "Inside folder: $PWD/$f"
        nextdir "$f"
        cd ..
        continue
   else
        echo "$PWD/$f"
   fi
done 
}
#call the function for the first time...
nextdir 

Save for example as recursive-loop and execute in the folder you want to do the search. It will do exactly what the find or other recursive mechanisms does, but using a for loop, and you can customize for your needs!

$./recursive-loop
/home/luciano/readme.txt
/home/luciano/images/a.bmp
/home/luciano/texts/a.txt
/home/luciano/texts/b.txt
/home/luciano/texts/music/lyrics.txt
(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.