0
Follow
5
View

Copy specific files from different directories without changing file extension

edith0312 注册会员
2023-01-26 06:41

...you want to use the subfolder name (number) as a suffix to the new file name, would you please try:

#!/bin/bash

folder="folder"                 # directory name
base="1"                        # basename of the jpg file
ext="jpg"                       # extention of the jpg file
new="new"                       # directory name for the "new" files

mkdir -p "$folder/$new"         # create "new" directory if nonexistent

while IFS= read -r -d "" f; do
    n=${f#*$folder/}; n=${n%/$base.$ext}
    echo cp -i -- "$f" "$folder/$new/$base($n).$ext"
done < <(find "$folder" -type f -regex "$folder/[0-9]+/$base\.$ext" -print0)
  • find "$folder" -type f -regex "$folder/[0-9]+/$base\.$ext" finds all numbered folders which contains "1.jpg". You do not have to specify the range between 1 and 100.
  • -print0 option uses a null character to delimit filenames. It is useful to protect filenames which may contain special characters such as blank characters.
  • The output of find command, matched filenames delimited by null characters, is redirected to the read command within the while loop.
  • The -d "" option to the read command splits the input on null characters corresponding to -print0.
  • n=${f#*$folder/}; n=${n%/$base.$ext} assigns n to the subfolder name which contains the jpg file.
  • "$folder/$new/$base($n).$ext" constructs the new filename rearranging the substrings.

If the output of the echo command looks okay, drop echo.

dlyss10000 注册会员
2023-01-26 06:41

...you accept a solution in two times?

  1. Run your find command
  2. Run this command:
for f in folder/new/*.~*~; do
  idx="${f##*.}";
  new=${f%.${idx}};
  idx="${idx//\~/}";
  ext="${new##*.}";
  new="${new%.${ext}}";
  new="${new}(${idx}).${ext}";
  echo mv "$f" "$new";
done

Only based on bash remove %, #, %% and ## matching patterns.

  1. get index pattern from original filename (f)
  2. new filename (new) is original filename without index extension (~*~)
  3. remove ~ characters in index token (idx)
  4. get original filename extension (ext)
  5. remove original filename extension in new filename
  6. create new filename (with format as you want)
  7. rename original filename to new filename

Notes:

  • Remove new line characters if you want (just here for presentation)
  • After test, remove echo before mv command.