根据 linux 中文件的特定字符创建子文件夹

create sub folders from specific characters of a file in linux

我有一个格式如下的文件test_YYYYMMDDHHMMSS.csv

test_20200328223607.csv
test_20190523112250.csv
test_20180201065548.csv

我需要重命名文件,然后根据其名称创建一个路径,然后将其添加到此格式的创建路径中 2020/03/28/223607.csv

示例: test_YYYYMMDDHHMMSS.csv => mkdir YYYY/MM/DD 从文件名然后 rename 文件成为 HHMMSS.csv 并将其添加到 YYYY/MM/DD

您可以使用 cut 来获取子字符串并以这种方式提取目录名称。可能有更清洁的解决方案,但像这样的方法应该有效

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

基于@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