0

I am having the following directory structures:

~/mydir/dir1/f1.jpg
~/mydir/dir1/f2.jpg

~/mydir/dir2/f3.jpg
~/mydir/dir2/f4.jpg
~/mydir/dir2/f5.jpg
~/mydir/dir2/f6.jpg

~/mydir/dir3/f7.jpg

i.e. directory (mydir) is having many subdirectories which in turn have many images in them. dir1, dir2 etc does not have any more subdirectories.

I am looking for a script (any language, shell, python etc) which can produce the output like:

<absolute path of f1.jpg> dir1
<absolute path of f2.jpg> dir1
<absolute path of f3.jpg> dir2
.
.
<absolute path of f6.jpg> dir2
<absolute path of f7.jpg> dir3

i.e. full absolute path of all the files in all the directories in mydir, followed by a space and then that file's directory (i.e. which last directory that file is in).

I am using find . -name \* -print to get the recursive file list but I am not sure how to get the exact output as desired.

My directory structure: enter image description here

sam
  • 95
  • 1
  • 1
  • 12
  • See: [bash/fish command to print absolute path to a file](http://stackoverflow.com/q/3915040/3776858) – Cyrus Mar 23 '16 at 21:27
  • You could use readlink -f ~/mydir/dirX/* where X is the number of your directory. – ar-ms Mar 23 '16 at 21:40

5 Answers5

3

Python

import os
for root, _, fnames in os.walk('/mydir'):
    for fname in fnames:
       print os.path.join(root, fname), fname
hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51
2

Use ls -d1 path/*/* for absolute path, then pipe it to Perl for printing in the particular format

ls -d1 ~/mydir/*/* | perl -lne 'print "<$_> ", m|.*/(.*)/[^/]*|'

The ~/ does get expanded to the absolute path. Output exactly as requested

</path_mydir/last_dir/filename> last_dir
...

If recursive listing is needed use path/** with shells that support it (most).

zdim
  • 64,580
  • 5
  • 52
  • 81
0

if you have find

find . -type f -printf "%f %h\n"

with the embellishments

find . -type f -printf "<absolute path of %f> %h\n"
karakfa
  • 66,216
  • 7
  • 41
  • 56
0
$ cd ~
$ find mydir -type f | perl -p -e 's|(.*)/([^/]+)\n$|\1/\2 \1\n|g'
mydir/dir1/f1.jpg mydir/dir1
mydir/dir1/f2.jpg mydir/dir1
mydir/dir2/f3.jpg mydir/dir2
mydir/dir2/f4.jpg mydir/dir2
mydir/dir2/f5.jpg mydir/dir2
mydir/dir2/f6.jpg mydir/dir2
mydir/dir3/f7.jpg mydir/dir3
NHDaly
  • 7,390
  • 4
  • 40
  • 45
0

You can use find `pwd` instead find . or find relatif_dir to take absolute path :

cd ~/mydir ; find `pwd`  -type f -name "*.jpg" -exec sh -c 'echo "<absolute path of "`basename {}`">" `dirname {}`' \;

or

 cd ~/mydir ; find `pwd`  -type f -name "*.jpg"  | sed -e "s/\(.*\)\/\([^\/]*\)/<absolute path of \2> \1/g"
Ali ISSA
  • 398
  • 2
  • 10