bashshelldirectorysubdirectorysha1sum

Bash / Shell script to modify files in folders and sub folders but NOT to modify folder names


So I have a script that goes through files in a folder and will rename them to odd and even numbers.

My Issue is I have allot of sub folders and it renames them to when I don't want to modify folder names but I do want to modify files inside the sub folders.

How can I achieve this ?

#!/bin/bash

export FILE_PATH="/path1/path2/path3/"
export even=0
export odd=-1

for file in /path1/path2/path3/*; do

mv "$file" $FILE_PATH$(echo "$file" | sed -e 's/[^A-Za-z0-9.]/_/g');

done

for f in /path1/path2/path3/*; do

sum=$(sha1sum "$f" | awk '{print $1}');

if [[ "$sum" != 3c72363260a32992c3ab2e3a5e9b8cf082e02b2c ]]; then

even=$((even+2));
echo $FILE_PATH"even_"$even".mp4";
mv "$f" $FILE_PATH""$even".mp4";

else

odd=$((odd+2));
echo $FILE_PATH"odd_"$odd".mp4";
mv "$f" $FILE_PATH""$odd".mp4";

fi;

done

Currently my directory layout is this.

/path1/path2/path3/random_folder_name/20.mp4

But the script keeps outputting this.

/path1/path2/path3/1/20.mp4

And I don't want my folder path modified just the mp4 renamed inside.


Solution

  • In each of the for loops the first thing you could do is check if the file in question really is a file or a directory, and react accordingly, eg:

    for file in /path1/path2/path3/*; do
        [[ -d "${file}" ]] && continue        # if it's a directory then skip to next pass through for loop
    
        mv "$file" ...
        ... snip ...
    done
    
    # and
    
    for f in /path1/path2/path3/*; do        # if it's a directory then skip to next pass through for loop
        [[ -d "${f}" ]] && continue
    
        sum= ...
        ... snip ...
    done
    

    NOTE: I'd suggest reviewing the man pages for bash for other tests as needed (eg, do you need to worry about symlinks? do you need to worry about executable files? do you need to worry about binary files?, etc)

    As for the separate issue of processing the files in a subdirectory ... see Nic3500's comment about using find -type f ... to provide a list of files at all directory levels; keep in mind this will require a redesign of your overall process (eg, replacing the 2x for loops with a single while loop).