Search code examples
bashrenamesubdirectory

create sub folders from specific characters of a file in linux


I have a files with the below format test_YYYYMMDDHHMMSS.csv

test_20200328223607.csv
test_20190523112250.csv
test_20180201065548.csv

I need to rename file then create a path from its name then add it to the created path with this format 2020/03/28/223607.csv

Example: test_YYYYMMDDHHMMSS.csv => mkdir YYYY/MM/DD from filename then rename file to be HHMMSS.csv and add it to YYYY/MM/DD


Solution

  • Based on an earlier answer by @Cyrus:

    #!/bin/bash
    
    # define a regular expression for use with the `[[` conditional command later on to match filename patterns
    re='^test_(....)(..)(..)(......)\.csv$'
    
    # iterate through all csv files in the current directory
    for i in *.csv; do
      # if filename does not match the regular expression, move on to the next loop iteration
      [[ "$i" =~ $re ]] || continue
      # the [[ conditional command leaves match results behind in an array variable named BASH_REMATCH
    
      # create a directory path using results; nop if directory already exists
      mkdir -p "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}/${BASH_REMATCH[3]}"
    
      # ... and relocate the file to the (newly created) directory whilst giving it a new name
      mv "$i" "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}/${BASH_REMATCH[3]}/${BASH_REMATCH[4]}.csv"
    done