【问题标题】:Move files to their respective folder in linux based on the date of the folder and the date of the file根据文件夹的日期和文件的日期将文件移动到linux中各自的文件夹
【发布时间】:2021-05-11 10:57:22
【问题描述】:

我对 bash 脚本和 linux 还很陌生,我有一个只有日期的文件夹,例如

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

我有名为 data_11202012_randomnumbers_csv 的文件。

我想创建一个脚本,通过将文件上的日期与文件夹匹配,可以将每个 csv 文件移动到正确的文件夹中。

我一直在输入 mv file path,但我有 100 多个文件,我想知道是否有更简单的方法。

任何帮助将不胜感激。

【问题讨论】:

  • 这些文件和目录是否在同一个目录中,并排放置?文件前缀是否总是data_
  • 是的,它们都在同一个目录中,是的,它总是数据

标签: linux bash ubuntu


【解决方案1】:

以下内容应该为您完成。我会用cmets解释

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 您有一个非常有用的 bash 备忘单,您可以在其中了解更多信息。它说明了我在 sn-p 中所做的所有变量扩展等等。

【讨论】:

  • 啊,非常感谢!备忘单有助于理解!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
相关资源
最近更新 更多