1

I have multiple directories, and each one of those directories contains an "example" directory which in turn contains images. What I want to do, is to add a textual suffix at the end of a filename (but which precedes the extension) to each file and then copy the contents of the directory into its respective parent directory.

Basically I want the files from /maindir/dir1/example/, /maindir/dir2/example etc. to be renamed and copied/moved to their respective parent directories, i.e. dir1 and dir2. The contents of all "example" dirs are images with a .jpg extension. I don't know if I am going about this the right way but I managed to figure out how to do the copying part by doing this:

find /path/to/folder/ -type d -name example  -execdir bash -c 'cp  "$1"/* .' cp {}   \;

which copies the content into the parent folder correctly, but I'm kinda stumped on how do I go about adding a suffix to the copied files while using find.

1
  • @Cbhihe I'm not sure I follow, basically I just want the files from /maindir/dir1/example/, /maindir/dir2/example etc. to be copied/moved to their respective parent directories, i.e. dir1 and dir2. Is that what you meant? The contents of all "example" dirs are images with the .jpg extensions. As long as the end result is the same using find is not required. As for collisions, the filenames are unique so that shouldn't be a problem, but I guess skipping already present files would be in order. the infix would be "-thumb" so image-thumb.jpg being the end result
    – user5672
    Jan 17, 2023 at 19:23

1 Answer 1

1

One way would be to use find and a for loop and for each file path use parameter expansion to extract the extension (t=${f##*.}), the basename (b=${f##*/}) and the basename without extension (${b%.*}) so as to be able to create the destination name (n=${b%.*}-thumb.${t}):

find /path/to/folder/ -type d -name example  -execdir sh -c 'for f in "${1}"/*;
do t=${f##*.}; b=${f##*/}; n=${b%.*}-thumb.${t}; cp -- "$f" "$n"; done' cp {} \;

You can always insert an echo before cp to print what would be executed.


Another way with zsh:

autoload zmv
zmv -n '(**/)example/(*)(.*)' '${1}${2}-thumb${3}'

Replace the -n (dry-run) with -C to copy the files.

1
  • Yes, that did exactly what I wanted. Thank you.
    – user5672
    Jan 18, 2023 at 10:49

You must log in to answer this question.

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