0

I am using Manjaro Gnu/Linux and I have a directory named files. Under this directory, I have around 650 sub directories, with names such as: dir1, dir2, dir3, dir4, ...

Under each sub directory there are varying number of .jpg images (say, from 2 to 11). Say as an example, under dir1 subdirectory, the images are imgaf001.jpg and srep0001.jpg.

I want to write a command/script to copy all such images to a new directory names all_images such that the images are renamed to the names of their sub directories.

For example: For dir1 sub directory, imgaf001.jpg changes to dir1_1.jpg and srep0001.jpg changes to dir1_2.jpg (after the underscore, the count of image comes).

How can I achieve this?

Thanks

1 Answer 1

1

You could run this script in the directory named files:

mkdir all_images
find -type f -name '*.jpg' -exec sh -c '
    c=1
    for f in "$@"; do
        pdir=${f%/*}
        pdir=${pdir##*/} #Now pdir conains the parent directory name
        cp -- "$f" "all_images/${pdir}_${c}.jpg"
        c=$((c+1))
    done
' findsh {} +

Sample directories with images:

$ ls dir*
dir1:
asj.jpg  assa.jpg

dir2:
kasj.jpg  kkl.jpg

After script execution:

$ ls all_images/
dir1_1.jpg  dir1_2.jpg  dir2_3.jpg  dir2_4.jpg

If you prefer the counter to be restarted upon source directory change, so that the result is dir1_1.jpg dir1_2.jpg dir2_1.jpg dir2_2.jpg, then do a little adaptation in the for loop:

mkdir all_images
find -type f -name '*.jpg' -exec sh -c '
    for f in "$@"; do
        pdir=${f%/*}
        pdir=${pdir##*/} #Now pdir conains the parent directory name
        [ "$pdir" != "$oldpdir" ] && c=1
        cp -- "$f" "all_images/${pdir}_${c}.jpg"
        oldpdir=$pdir
        c=$((c+1))
    done
' findsh {} +

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .