【问题标题】:create sub folders from specific characters of a file in linux从linux中文件的特定字符创建子文件夹
【发布时间】:2020-03-31 18:03:53
【问题描述】:

我有一个格式如下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

【问题讨论】:

  • 嗨。欢迎来到堆栈溢出!您对“>>”的使用让我有些困惑。这在 bash 中具有不符合上下文的特定含义。你能解释一下或者重写一下更清楚吗?
  • @Cyrus 你的回答怎么了?

标签: bash rename subdirectory


【解决方案1】:

根据@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

【讨论】:

  • 你能解释一下这个脚本吗
  • @AhmedAmer 我添加了内联 cmets
  • @Cyrus 非常感谢
  • 是否可以重新通过不同的文件名,如 test fest dest
  • 当然您可以用^(test|fest|dest|foo)_... 替换^test_...,但是您必须将所有BASH_REMATCH[n] 引用更改为BASH_REMATCH[n+1],以考虑额外的括号也进行匹配。
【解决方案2】:

您可以使用 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

【讨论】:

  • 添加一个shebang,然后将您的脚本粘贴到那里:shellcheck.net
猜你喜欢
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-13
  • 2017-08-21
相关资源
最近更新 更多