简体   繁体   中英

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

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

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:

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM