Home > Software engineering >  How to rename all the files across different folders into another folder using count in the name?
How to rename all the files across different folders into another folder using count in the name?

Time:09-27

I am under Ubuntu and I would like to write a bash script such that the following configuration is changed from:

--images
  |--video1
  |  |--frame1.jpg
  |  |--frame2.jpg
  |  |-- ...
  |  |--frame32.jpg
  |
  |--video2
  |  |--frame1.jpg
  |  |--frame2.jpg
  |  |-- ...
  |  |--frame32.jpg
  |
  |-- ...
  |
  |--video900
  |  |--frame1.jpg
  |  |--frame2.jpg
  |  |-- ...
  |  |--frame32.jpg

to

|--images
|--final_images
|  |--frame1.jpg
|  |--frames2.jpg
|  |-- ...
|  |--frame28800.jpg

My goal is to move all the frames for each video in the same directory final_images. So first I would like to go into every folder and rename every frame such that to frame1, frame2,..., frame28800 (every video has 32 frames and I have 900 videos so the total number of frames I have is 28800). Then I would like to move all the renamed frames into final_images. Any help would be appreciated, I am not very proficient with bash.

Edit: This is what I tried, being in images folder:

A=0; 
for i in $(ls -d */); do 
    for file in $(ls ${i%%} */); do 
       mv "$(pwd)/${i%%}${file%%}" "$(pwd)/${i%%}${file%%}_$A" ;  
       ((A  )); 
       echo $A ;  
    done ; 
done

CodePudding user response:

These could be the algorithm steps:

  • initialize a count variable
  • get all files from source dir
  • exclude directories. We need just files
  • copy the source file to the target folder, renaming it using the count variable
  • increase the count variable
source_folder=$1
target_folder=$2

mkdir -p $target_folder

echo "procesing..."
count=1
for file in $source_folder/* $source_folder/**/* ; do

  if [[ -f $file ]]; then

    cp  $file $target_folder/frame$count.jpg
    echo "source:"$file "target:"$target_folder/frame$count.jpg
    count=$((count   1))

  else
      echo "$file is not valid or is folder"
  fi
done;

echo ""
echo "target_folder: $target_folder"
find  $target_folder | sort

Save this and execute with this parameters:

bash merge_frames.sh /tmp/workspace/source/ /tmp/workspace/target

result:

result

CodePudding user response:

If those numbers are fixed, you can do:

for v in {1..900}; do
  for f in {1..32}; do
    mv video$v/frame$f.jpg ../final_images/frame$(((v-1)*32 f)).jpg
  done
done

If only the number of frames per directory is fixed, then:

for vd in video*; do
  v=${vd#video}
  for f in {1..32}; do
    mv $vd/frame$f.jpg ../final_images/frame$(((v-1)*32 f)).jpg
done
  • Related