I have a bunch of files, in many folders and I wanted to create txt file with full paths to this files and with space and name of the directory they are in. something like:

halva/foo/bar/1/something.jpg 1
halva/foo/bar/2/another.jpg 2
halva/foo/bar/2/anotheranother.jpg 2

Creating a list of paths is something like

find `pwd` -name *.jpg

But I don't know how to add space and directory name after the path. I'm trying to categorize stuff for school project.

$ find .  -name *.jpg -exec bash -c 'd=${1%/*}; d=${d##*/}; printf "%s %s\n" "$1" "$d"' Out {} \;
./halva/foo/bar/1/something.jpg 1
./halva/foo/bar/2/another.jpg 2
./halva/foo/bar/2/anotheranother.jpg 2

For every file found by find, we run the bash script d=${1%/*}; d=${d##*/}; printf "%s %s\n" "$1" "$d" where the first argument, $1, is the file name.

We use suffix removal, d=${1%/*}, to obtain the directory name from the full file name. We then use prefix removal, d=${d##*/}, to remove all but the name of the last directory from d. Lastly, printf is used to print the output.

The string Out in the above command is not used unless there is an error in the bash command in which case it functions as the effective command name, $0.

Saving the output to a file

To save the output to a file, we use redirection:

find .  -name *.jpg -exec bash -c 'd=${1%/*}; d=${d##*/}; printf "%s %s\n" "$1" "$d"' Out {} \; >SchoolProject.txt

The > symbol redirects stdout to the file name which follows it.

  • Great work! He should append ` > SchoolProject.txt` to your command to get his text file though. – WinEunuuchs2Unix Sep 13 '16 at 18:38
  • Thanks for quick response :) I got an error while using this command find: missing argument to `-exec' EDIT: It works like charm! thank You :D – Piteight Sep 13 '16 at 18:41
  • 1
    @WinEunuuchs2Unix OK. Example with redirection included. – John1024 Sep 13 '16 at 18:41
  • missing argument to '-exec': That error happens if the final \; is missing from the command. – John1024 Sep 13 '16 at 18:43
  • @Piteight if the software allows you, don't forget to up-vote John's answer so he gains reputation points within AskUbuntu. – WinEunuuchs2Unix Sep 13 '16 at 19:03

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.