根据bash中的编号将文件夹分隔到子文件夹中

时间:2016-08-04 09:57:45

标签: bash

我有以下目录树:

str.format()

文件夹订购中可能缺少数字。

我想根据数字将这些文件夹分成子文件夹,以便所有数字小于6的文件夹(在第二个1_loc 2_buzdfg 4_foodga 5_bardfg 6_loc 8_buzass 9_foossd 12_bardaf 文件夹之前)转到_loc,所有文件夹都带有数字等于或大于6,转到folder1

我当然可以使用鼠标轻松解决问题,但我想从终端自动建议如何做到这一点。

有什么想法吗?

6 个答案:

答案 0 :(得分:2)

我认为解决方案是循环访问文件并在第一个_Alignof之前检查数字。

首先,让我们检查如何获取_之前的数字:

_

好的,这样可行。然后,让我们循环:

$ d="1_loc_b"
$ echo "${d%%_*}"
1

答案 1 :(得分:2)

while read -r line; do
    # Regex match the beginning of the string for a character between 1 and 5 - change this as you'd please to any regex
    FOLDERNUMBER=""
    [[ "$line" ~= "^[1-5]" ]] && FOLDERNUMBER="1" || FOLDERNUMBER="2"

    # So FOLDERPATH = "./folder1", if FOLDERNUMBER=1
    FOLDERPATH="./folder$FOLDERNUMBER"

    # Check folder exists, if not create it
    [[ ! -d "$FOLDERPATH" ]] && mkdir "$FOLDERPATH"

    # Finally, move the file to FOLDERPATH
    mv "$line" "$FOLDERPATH/$(basename $line)"
done < <(find . -type f)
# This iterates through each line of the command in the brackets - in this case, each file path from the `find` command.

答案 2 :(得分:1)

假设folder1folder2存在于同一目录中,我会这样做:

for d in *_*; do # to avoid folder1 and folder2
    # check if the first field seperated by _ is less than 5 
    if ((`echo $d | cut -d"_" -f1` < 6)); then 
         mv $d folder1/$d; 
    else 
         mv $d folder2/$d; 
    fi; 
done

(更多关于cut

答案 3 :(得分:1)

您可以转到当前目录并运行以下简单命令:

mv {1,2,3,4}_* folder1/
mv {5,6,7,8}_* folder2/ 

这假设没有其他文件/目录以这些前缀开头(即1-8)。

答案 4 :(得分:1)

另一种纯bash参数扩展解决方案: -

#!/bin/bash

# 'find' returns folders having a '_' in their names, the flag -print0 option to 
#  preserve special characters in names.

#  the folders are names as './1_folder', './2_folder', bash magic is done
#  to remove those special characters.

# '-v' flag in 'mv' for verbose action

while IFS= read -r -d '' folder; do

    folderName="${folder%_*}"     # To strip the characters after the '_'
    finalName="${folderName##*/}" # To strip the everything before '/'

    ((finalName > 5)) && mv -v "$folder" folder1 || mv -v "$folder" folder2

done < <(find . -maxdepth 1 -mindepth 1 -name "*_*" -type d -print0)

答案 5 :(得分:1)

您可以使用以下代码创建脚本,并在运行时,将根据需要移动文件夹。

#seperate the folders into 2 folders
#this is a generic solution for any folder that start with a number
#!/bin/bash
for file in *
do
prefix=`echo $file | awk 'BEGIN{FS="_"};{print $1}'`

if [[ $prefix != ?(-)+([0-9]) ]]
then continue
fi

if [ $prefix -le 4 ]
then mv "$file" folder1

elif [ $prefix -ge 5 ]
then mv "$file" folder2

fi

done