繁体   English   中英

如何使bash脚本按特定编号对文件夹中的文件进行分类

[英]How to make a bash script classify files in folders by a specific number

我在StackOverflow上找到了一个脚本,我对其做了一些修改。 该脚本将子文件夹中文件夹中的所有文件分类,每个子文件夹中只有8个文件。 但是我有这样名称的文件0541_2pcs.jpg。 2pcs表示两件(副本)。

因此,我希望脚本在将文件划分到每个文件夹时考虑到这一点。 例如,一个文件夹可能包含6个文件,而这个0541_2pcs.jpg实际意味着2个文件,依此类推,具体取决于文件名中指示的编号。

这是脚本:

cd photos;
dir="${1-.}"
x="${1-8}"

let n=0
let sub=0
while IFS= read -r file ; do
    if [ $(bc <<< "$n % $x") -eq 0 ] ; then
            let sub+=1
            mkdir -p "Page-$sub"
            n=0
    fi

    mv "$file" "Page-$sub"
    let n+=1
done < <(find "$dir" -maxdepth 1 -type f)

谁能帮我?

您可以通过[ ${file/2pcs/x} != $file ]这样的代码来添加文件名是否包含字符串“ 2pcs”的测试。 在下面显示的脚本中,如果该测试成功,则第二次增加n 请注意,如果第八个文件被测试要包含在目录中,则它是一个多段文件,那么在该目录中最终会有一个文件太多。 可以通过脚本不执行的其他测试来解决。 请注意,您的脚本没有充分的理由调用bc进行模量计算,并且从第一个参数设置dirx均无效。 我的脚本使用两个参数。

#!/bin/bash

# To test pagescript, create dirs four and five in a tmp dir.
# In four, say
#    for i in {01..30}; do touch $i.jpg; done
#    for i in 03 04 05 11 16 17 18; do mv $i.jpg ${i}_2pcs.jpg; done
# Then in the tmp dir, say
#     rm -rf Page-*; cp four/* five/; ../pagescript five; ls -R

#cd photos;   # Leave commented out when testing script as above
dir="${1-.}"  # Optional first param is source directory
x=${2-8}      # Optional 2nd param is files-per-result-dir

let n=x
let sub=0
for file in $(find "$dir" -maxdepth 1 -type f)
do  # Uncomment next line to see values as script runs 
    #echo file is $file, n is $n, sub is $sub, dir is $dir, x is $x
    if [ $n -ge $x ]; then
        let sub+=1
        mkdir -p Page-$sub
        n=0
    fi
    mv "$file" Page-$sub
    [ ${file/2pcs/x} != $file ] && let n+=1
    let n+=1
done  

暂无
暂无

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

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