文件处理和制作目录以在 bash 中匹配

File Handling and making directories to match in bash

我有这些文件:File_1.2.txtFile_1.5.txtFile_2.3.txtFile_4.7.txt

我想给他们做个目录,然后把他们分类到目录里,如下图。

Dir_001 -> File_1.2.txt File_1.5.txt 

Dir_002 -> File_1.2.txt File_2.3.txt

Dir_003 -> File_2.3.txt 

Dir_004 -> File_4.7.txt 

Dir_005 -> File_1.5.txt 

Dir_007 -> File_4.7.txt

因此,为文件使用的每个编号创建一个目录,并将包含目录匹配编号的所有文件分类到其中。

你至少应该自己试过这个。仅仅复制别人的代码并不是一个好的学习方式。

有几种方法可以做到这一点,这是我的,你的呢?

#!/bin/bash

function make_dir
{
    #name="Dir00"
    # Cribbed from the answer given by @Cyrus
    printf -v name "Dir_%03d" ""

    echo "$name"
    if [[ ! -d $name ]]
    then
        mkdir "$name"
    fi
}

# I don't need an array here, but I have no idea where these filenames come from
filenames=(File_1.2.txt File_1.5.txt File_2.3.txt File_4.7.txt)

for fname in ${filenames[@]}
do
    for seq in {1..999}      # No idea what the upper limit should be
    do
        #if [[ $fname == *$seq* ]]
        # Edit: to handle multi-character sequences
        if [[ $fname == *[_.]$seq.* ]] 
        then
            dir=$(make_dir $seq)
            cp "$fname" "$dir"
        fi
    done
done

其他人无疑会对此进行改进。

编辑函数和序列。

#!/bin/bash

# If there are no files match File_*.*.txt
# replace File_*.*.txt by empty string
shopt -s nullglob 

for i in File_*.*.txt; do
  echo "processing file $i"
  IFS="_." read foo num1 num2 foo <<< "$i"
  printf -v dir1 "Dir_%03d" "$num1"
  printf -v dir2 "Dir_%03d" "$num2"
  mkdir -pv "$dir1" "$dir2"
  cp -v "$i" "$dir1"
  cp -v "$i" "$dir2"
done