Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script to copy and prepend folder name to files from multiple subdirectories

I have several folders with different images sharing file names, with a folder structure like this:

/parent/folder001/img001.jpg
/parent/folder001/img002.jpg
/parent/folder002/img001.jpg
/parent/folder002/img002.jpg
/parent/folder003/img001.jpg
/parent/folder003/img002.jpg
...

and would like to copy/rename these files into a new folder, like this:

/newfolder/folder001_img001.jpg
/newfolder/folder001_img002.jpg
/newfolder/folder002_img001.jpg
/newfolder/folder002_img002.jpg
/newfolder/folder003_img001.jpg
/newfolder/folder003_img002.jpg
...

(It's probably better if newfolder isn't a subfolder of parent, since that might end up causing really weird recursion.)

None of the folders containing images have any subfolders.

Ideally, I'd like to be able to reuse the script to "update" newfolder, since I might need to add more folders-containing-images later along the line.

How can I accomplish this with a shell script?

like image 944
Nekkowe Avatar asked Apr 28 '15 13:04

Nekkowe


1 Answers

This is a bit tedious but will do:

#!/bin/bash
parent=/parent
newfolder=/newfolder
mkdir "$newfolder"
for folder in "$parent"/*; do
  if [[ -d "$folder" ]]; then
    foldername="${folder##*/}"
    for file in "$parent"/"$foldername"/*; do
      filename="${file##*/}"
      newfilename="$foldername"_"$filename"
      cp "$file" "$newfolder"/"$newfilename"
    done
  fi
done

Put the parent path to parent variable and newfolder path to newfolder variable.

like image 50
Jahid Avatar answered Sep 20 '22 12:09

Jahid