Danish M
Danish M

Reputation: 105

Move files to their respective folder in linux based on the date of the folder and the date of the file

I'm fairly new to bash scripting and linux, and I have a folders with just dates such as

2012-11-20
2012-11-21
2012-11-22
2012-11-23

and I have files with the name data_11202012_randomnumbers_csv.

I would like to create a script that can move every single csv file to it's correct folder by matching the date on the file to the folder.

I've been just typing mv file path but i have 100s of files and I'm wondering if theres an easier way.

Any help would be appreciated.

Upvotes: 0

Views: 286

Answers (1)

Miguel
Miguel

Reputation: 2219

The following should do it for you. I will explain with comments

for file in your_folder/*; do
  # 1. Extract the numbers from the file name
  dir="${file#data_}" # remove data_ prefix
  dir="${dir%%_*}" # remove everything after first _

  # 2. Rearrange the numbers into the desired format
  dir="${dir:2:4}-${dir:0:2}-${dir:6:2}"
  
  # 3. Move the file into the directory
  mv file dir
done

Here you have a very useful bash cheatsheet where you can learn more about it. It illustrates all the variable expansions I've made in my snippet and more.

Upvotes: 2

Related Questions