【问题标题】:Bash script to rename file names with correct date format in all sub folders in Linux在 Linux 中的所有子文件夹中使用正确日期格式重命名文件名的 Bash 脚本
【发布时间】:2016-01-02 08:23:30
【问题描述】:

我有大量的日志名称为“filename.logdate month year”(例如,filename.log25 Aug 2015 ,请注意日期/月/年之间有空格),我想将它们更改为“filename.logmonthdateyear”(例如 filename.logOct052015 ,没有空格)。 这些文件位于一堆子文件夹中,这使其更具挑战性。

父文件夹 --- 子文件夹1 文件1 文件2 --- 子文件夹2 文件 3 文件4 等等

谁能推荐一个可以做到这一点的 bash 脚本? 谢谢!

【问题讨论】:

  • 欢迎来到 StackOverflow。请参阅stackoverflow.com/help/how-to-askstackoverflow.com/help/mcve。我们可以帮助您编写脚本。我们不接受 StackOverflow 的编码任务。 /// 您需要编写一个简短的脚本来提取日期(关闭“.log”),将其分成三个部分,然后按照您想要的顺序重新组合它们。我还建议您将年份放在首位,也许将月份更改为数字,例如 .log2015-10-05,因为这样您可以轻松地将文件按时间顺序排序。

标签: linux bash date


【解决方案1】:

findrename 应该可以解决问题

稻草人示例:

离开

...
├── foo/
│   ├── file name with spaces
│   └── bar/
│       └── another file with spaces
...

你可以使用

find foo/ -type f -exec rename 's/ //g' '{}' \;

得到

...
├── foo/
│   ├── filenamewithspaces
│   └── bar/
│       └── anotherfilewithspaces
...

在你的情况下:

在你的情况下,它会像

find path/to/files/ -type f -exec rename 's/ //g' '{}' \;

但您可以在 find 命令中使用更高级的过滤器,例如

find path/to/files/ -type f -name *.log* -exec rename 's/ //g' '{}' \;

仅选择 .log 文件,以防其他文件名包含您不想触摸的空格


注意:

正如 cmets 中所指出的,如果文件的名称仅因空间位置而异(例如,a bc.logab c.log,如果不小心重命名,则可能会覆盖文件。 987654331@).

对于你的情况,你有两件事:

  1. rename 会提醒您,只要您不使用它的 --force 选项 并且会给你一个有用的信息,比如./ab c.log not renamed: ./abc.log already exists
  2. 您的文件是以编程方式命名的,并且您正在去除日期中的空格,因此,假设您拥有的就是其中的所有内容,那么您应该没有任何问题

不管怎样,留心这种事情就好了

【讨论】:

  • 要小心,因为这样减少文件名可能会导致冲突。映像同一目录中的两个文件a bc.txtab c.txt
  • 请注意,如果 dirname 包含空格,则会失败!如果您的find 支持-execdir,则使用它,否则您必须以不同的方式进行。
  • 我认为您错过了问题中需要交换日期格式的粗体部分。他们不仅需要删除空格,还需要从D M Y 切换到MDY
【解决方案2】:

这是一种只使用 Bash (4+) 和 'mv' 的方法:

# Prevent breakages when nothing matches patterns
shopt -s nullglob

# Enable '**' matches (requires Bash 4)
shopt -s globstar

topdir=$PWD
for folder in **/ ; do
    # Work in the directory to avoid problems if its path has spaces
    cd -- "$folder"
    for file in *' '*' '* ; do
        # Use the '-i' option to prevent silent clobbering
        mv -i -- "$file" "${file// /}"
    done
    cd -- "$topdir"
done

如果只有一层子文件夹(如问题中所述),则可以放弃对 Bash 4+ 的要求:删除shopts -s globstar,并将外循环的第一行更改为for folder in */ ; do

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2017-10-02
    • 1970-01-01
    • 2016-04-30
    • 2010-12-29
    • 2011-12-30
    相关资源
    最近更新 更多