简体   繁体   English

BASH遍历文件夹和文件

[英]BASH loop through folders and files

I have a problem with listing through directories. 我在通过目录列出时遇到问题。 I wanted to make script which will loop through dirs and files in them so I can move them elsewhere. 我想制作一个脚本,该脚本将遍历目录中的目录和文件,以便将它们移至其他位置。

My problem is that I need to SORT all the files within the folders. 我的问题是我需要对文件夹中的所有文件进行排序。 There's like 2000 directories and I need to loop through them and then loop through all files within these dirs and sort them by extension in directory which will be created (or files will be moved) and it's name will be that particular extension 大约有2000个目录,我需要遍历它们,然后遍历这些目录中的所有文件,并按扩展名对它们进行排序,该目录将被创建(或文件将被移动),名称将是该特定扩展名

Could anyone help? 有人可以帮忙吗?

#!/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 are quoting the wildcard, so you are looking for files whose name literally ends with the character * . 您引用的通配符,所以你正在寻找的文件名称以字符字面结束*

Anyway, you should not use ls to drive loops , and also, you should avoid using uppercase for your private variables. 无论如何, 您不应使用ls来驱动循环 ,并且,也应避免对私有变量使用大写字母。

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

I'm not sure I understand exactly what the innermost loop is supposed to accomplish, so there is some guesswork there. 我不确定我是否完全了解最内层的循环应该完成什么,所以在那里有些猜测。 The general idea is to pass the destination directory in $0 (obscure hack, but it's fairly common) and the found files to the -exec script. 一般的想法是将目标目录传递给$0 (晦涩的hack,但这很普遍),然后将找到的文件传递给-exec脚本。

You can make use of ls command 您可以使用ls命令

cd $HOME/Desktop/try/
ls -laRX

OR 要么

ls -laRX $HOME/Desktop/try/

   -l     use a long listing format
   -a, --all do not ignore entries starting with .
   -R, --recursive
          list subdirectories recursively
   -X     sort alphabetically by entry extension

Refer man ls for more information 请参阅man ls以获取更多信息

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

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