Reputation: 1
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
Upvotes: 0
Views: 157
Reputation: 2610
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
Upvotes: 1
Reputation: 399
You can use cut to get substrings and extract the directory names that way. There may be a cleaner solution but something like this should work
for i in *.csv
do
# split the string
IFS='_'
read -ra ADDR <<< "$i"
year=$(echo "${ADDR[1]}" | cut -c1-4)
... get other sub strings ...
path=${year}/${month}/etc
mkdir -p "$path"
mv "$i" "${path}"/"${seconds}".csv
done
Upvotes: 0