Bash:根据名字的第一个字母移动文件

时间:2012-05-22 00:15:33

标签: bash

我有大量的文件,我试图按字母顺序组织成三个文件夹。我正在尝试将bash脚本放在一起,它能够获取文件的第一个字母,然后将其移动到基于该第一个字母的文件夹中。

例如:

file - >文件夹名称

apples - >甲-G

banana - >甲-G

番茄 - > H-Ť

斑马 - > ù-Z

任何提示将不胜感激! TIA!

3 个答案:

答案 0 :(得分:6)

#!/bin/bash
dirs=(A-G H-T U-Z)
shopt -s nocasematch

for file in *
do
    for dir in "${dirs[@]}"
    do
        if [[ $file =~ ^[$dir] ]]
        then
            mv "$file" "$dir"
            break
        fi
    done
done

答案 1 :(得分:2)

您需要substring expansioncase statement。例如:

thing=apples
case ${thing:0:1} in
    [a-gA-G]) echo "Do something with ${thing}." ;;
esac

答案 2 :(得分:0)

添加我的代码 - 这是99%基于Dennis Williamson - 我刚刚添加了一个if块以确保你没有将dir移动到目标目录中,我想要每个字母一个dir。

#!/bin/bash
dirs=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
shopt -s nocasematch

for file in *
do
    for dir in "${dirs[@]}"
    do

     if [ -d "$file" ]; then
      echo 'this is a dir, skipping'
      break
     else
      if [[ $file =~ ^[$dir] ]]; then
       echo "----> $file moves into -> $dir <----"
       mv "$file" "$dir"
       break
      fi
     fi
  done
done