Xarz Xarz - 6 months ago 23
Linux Question

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

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

Answer

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.

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