简体   繁体   English

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

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

I found a script, here on StackOverflow, which I modified a little. 我在StackOverflow上找到了一个脚本,我对其做了一些修改。 The script classifies all files from a folder in subfolders, each subfolder having only 8 files. 该脚本将子文件夹中文件夹中的所有文件分类,每个子文件夹中只有8个文件。 But I have files with such names 0541_2pcs.jpg. 但是我有这样名称的文件0541_2pcs.jpg。 2pcs means two pieces (copies). 2pcs表示两件(副本)。

so I would like the script to take this into count when dividing files to each folder. 因此,我希望脚本在将文件划分到每个文件夹时考虑到这一点。 eg a folder may have 6 files and this 0541_2pcs.jpg which literally means 2 files and so on, depending on the number indicated in the file's name. 例如,一个文件夹可能包含6个文件,而这个0541_2pcs.jpg实际意味着2个文件,依此类推,具体取决于文件名中指示的编号。

This is the script: 这是脚本:

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)

Can anyone help me? 谁能帮我?

You can add a test for whether a file name contains the string "2pcs" via code like [ ${file/2pcs/x} != $file ] . 您可以通过[ ${file/2pcs/x} != $file ]这样的代码来添加文件名是否包含字符串“ 2pcs”的测试。 In the script shown below, if that test succeeds then n is incremented a second time. 在下面显示的脚本中,如果该测试成功,则第二次增加n Note, if the eighth file tested for inclusion in a directory is a multi-piece file, you will end up with one too many files in that directory. 请注意,如果第八个文件被测试要包含在目录中,则它是一个多段文件,那么在该目录中最终会有一个文件太多。 That could be handled by additional testing the script doesn't do. 可以通过脚本不执行的其他测试来解决。 Note, there's no good reason for your script to call bc to do a modulus, and setting both of dir and x from the first parameter doesn't work; 请注意,您的脚本没有充分的理由调用bc进行模量计算,并且从第一个参数设置dirx均无效。 my script uses two parameters. 我的脚本使用两个参数。

#!/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