简体   繁体   English

使用bash批量移动和重命名文件

[英]Batch move and rename files with bash

I have lots of files in a structure like this. 我在这样的结构中有很多文件。 There are .py files inside folder with the name std01 ... std60 文件夹中有.py文件,名称为std01 ... std60

/std01 (directory)
    problem1.py
    problem2.py
    problem3.py
/std02 (directory)
    problem1.py
    problem2.py
    problem3.py

By using bash commands, can I move and rename those files, so that it would be in a folder by the file name, leading by the std folder name? 通过使用bash命令,我可以移动和重命名那些文件,以便将其放置在文件夹中的文件名下,以std文件夹名开头吗?

/problem1.py (directory)
    std01_problem1.py
    std02_problem1.py
    ...
/problem2.py (directory)
    std01_problem2.py
    std02_problem2.py
    ...
for std in *; do
    for problem in "$std"/*; do
        problem=${std##*/}    # trim directory name
        mkdir -p "$problem"   # create dir if it doesn't already exist
        mv "$std/$problem" "$problem/$std_$problem"
    done

    rmdir "$std"   # if original directory is empty, remove it
 done

find + bash solution: find + bash解决方案:

Before: 之前:

$ tree std*
std01
├── problem1.py
├── problem2.py
└── problem3.py
std02
├── problem1.py
├── problem2.py
└── problem3.py

find . -type f -path "*std[0-9]*/problem[0-9]*.py" -exec bash -c \
'IFS=/ read -ra a <<<"$1"; mkdir -p "${a[-1]}"; mv "$1" "${a[-1]}/${a[-2]}_${a[-1]}"' _ {} \;

After: 后:

$ tree problem*
problem1.py
├── std01_problem1.py
└── std02_problem1.py
problem2.py
├── std01_problem2.py
└── std02_problem2.py
problem3.py
├── std01_problem3.py
└── std02_problem3.py

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

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