简体   繁体   English

Linux:按名称顺序将多个文件批量重命名为父目录+后缀

[英]Linux: Batch rename multiple files to parent dir + suffix in order of name

I need to batch rename multiple images and want to use the parent directory as base name. 我需要批量重命名多个图像,并想使用父目录作为基本名称。 To prevent one overwriting the other, a suffix must be added. 为防止一个覆盖另一个,必须添加后缀。 The order of the renaming process musts follow the timestamp of the file. 重命名过程的顺序必须遵循文件的时间戳。 Because the 'first' file is a featured image for the site I'm using it for. 因为“第一个”文件是我正在使用的网站的特色图片。

Tree: 树:

└── main
├── white tshirt
│   ├── IMG_1.jpg
│   ├── IMG_2.jpg
│   ├── IMG_3.jpg
│   └── IMG_4.jpg
├── black tshirt
│   ├── IMG_1.jpg
│   ├── IMG_2.jpg
│   ├── IMG_3.jpg
│   └── IMG_4.jpg
└── red tshirt
    ├── IMG_1.jpg
    ├── IMG_2.jpg
    ├── IMG_3.jpg
    └── IMG_4.jpg

Goal: 目标:

└── main
├── white tshirt
│   ├── white-tshirt-1.jpg
│   ├── white-tshirt-2.jpg
│   ├── white-tshirt-3.jpg
│   └── white-tshirt-4.jpg
├── black tshirt
│   ├── black-tshirt-1.jpg
│   ├── black-thisrt-2.jpg
│   ├── black-tshirt-3.jpg
│   └── black-tshirt-4.jpg
└── red tshirt
    ├── red-tshirt-1.jpg
    ├── red-tshirt-2.jpg
    ├── red-tshirt-3.jpg
    └── red-tshirt-4.jpg

Replacing spaces with dashes is not required, but preferred. 不需要用破折号代替空格,但首选。 Platform: Debian 8 平台:Debian 8

I think this should do the job: 我认为这应该可以做到:

#!/bin/sh

for dir in *; do
    if [ ! -d "$dir" ]; then
        continue
    fi

    cd "$dir"

    pref=$(echo "$dir" | tr ' ' -)

    i=1
    ls -tr | while read f; do
        ext=$(echo "$f" | sed 's/.*\.//')
        mv "$f" "${pref}-${i}.$ext"
        i=$(expr $i + 1)
    done

    cd ..
done

Invoke the script inside your main directory and make sure there are only your target folders in it. 在主目录中调用脚本,并确保其中仅包含目标文件夹。 Also make sure your files'names do not contain the character '\\' 另外,请确保您文件的名称中不包含字符“ \\”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM