gpt4 book ai didi

linux - BASH 遍历文件夹和文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:39 30 4
gpt4 key购买 nike

我在通过目录列出时遇到问题。我想制作一个脚本来循环遍历其中的目录和文件,以便我可以将它们移动到其他地方。

我的问题是我需要对文件夹中的所有文件进行排序。大约有 2000 个目录,我需要遍历它们,然后遍历这些目录中的所有文件,并在将创建的目录中按扩展名对它们进行排序(或将移动文件),它的名称将是特定的扩展名

有人能帮忙吗?

#!/bin/bash

tar_fol="$HOME/Desktop/try/"
to_fol="$HOME/Desktop/SortedFiles/"

for DIRE in "$(ls -d $tar_fol"*")"
do

echo "Checking dir : $DIRE"

for FIL in "$(ls -p $tar_fol$DIRE)"
do
echo "Checking file : $FIL"

if [ "$(find ~/Desktop/ -type d -name ${FIL##*.})" != "" ]
then
mv -f $tar_fol$FIL $to_fol${FIL##*.}
else
mkdir $to_fol${FIL##*.}
mv $tar_fol$FIL $to_fol${FIL##*.}
fi

done
done

最佳答案

您正在引用通配符,因此您正在查找名称​​字面上以字符 * 结尾的文件。

无论如何,you should not use ls to drive loops ,而且,您应该避免对私有(private)变量使用大写字母。

#!/bin/bash

tar_fol="$HOME/Desktop/try/"
to_fol="$HOME/Desktop/SortedFiles/"

for dire in "$tar_fol"/*/.
do
echo "Checking dir: '$dire'"
for fil in "$dire"/*
do
echo "Checking file: '$fil'"
find ~/Desktop/ -type d -name "${fil##*.}" -exec sh -c 'mkdir -p "$0";
mv "$@" "$0"' "$to_fol" "$fil" {} \+
done
done

我不确定我是否完全理解最内层循环应该完成什么,所以那里有一些猜测。一般的想法是将目标目录传递到 $0(晦涩的 hack,但它很常见)和找到的文件到 -exec 脚本。

关于linux - BASH 遍历文件夹和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37609197/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com