繁体   English   中英

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

[英]Bash: Move files based on first letter of name

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

例如:

文件 - >文件夹名称

苹果 - > AG

香蕉 - > AG

番茄 - > HT

斑马 - > UZ

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

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

您想要子字符串扩展case语句 例如:

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

添加我的代码 - 这是99%基于Dennis Williamson - 我刚刚添加了一个if块以确保你没有将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

暂无
暂无

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

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