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

时间:2017-10-09 13:38:10

标签: bash

我在这样的结构中有很多文件。文件夹中有.py个文件,名称为std01 ... std60

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

通过使用bash命令,我可以移动和重命名这些文件,以便按文件名在文件夹中,以std文件夹名称引导吗?

/problem1.py (directory)
    std01_problem1.py
    std02_problem1.py
    ...
/problem2.py (directory)
    std01_problem2.py
    std02_problem2.py
    ...

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

find + bash 解决方案:

在:

$ 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]}"' _ {} \;

后:

$ 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
相关问题