Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SH script to move files from one dir to another depending on the filename

Tags:

bash

shell

I am trying to write a sh script that will run when one of my downloads is completed.

It should look for a specific filename on ~/Downloads and move it to a different dir depending on the filename.

I.e. I have downloaded the last episode of Glee, the filename is:

glee_some_trash_files_always_have.mkv

It should be moved to

~/TVshows/Glee/

This is what I was able to do:

#!/bin/bash

if filename in ~/Downoads; then
result=
if filename = *glee*; then
result= mv $filename ~/TVshows/Glee/
else
if filename = *pokemon*; then
result= mv $filename ~/TVshows/pokemon/
endif
done

Is my approach correct? Please note I am very new to sh.

Thanks in advance.

###############################################################################

Edit: Here is my script, I hope someone else could find it useful:

#!/bin/bash

cd "$HOME/Downloads"
# for filename in *; do
find . -type f | while IFS= read filename; do # Look for files in all ~/Download sub-dirs
  case "${filename,,*}" in  # this syntax emits the value in lowercase: ${var,,*}  (bash version 4)
     *.part) : ;; # Excludes *.part files from being moved
     move.sh) : ;;
#    *test*)            mv "$filename" "$HOME/TVshows/Glee/" ;; # Using move there is no need to {&& rm "$filename"}
     *test*)           scp "$filename" "[email protected]:/users/imac/Desktop/" && rm "$filename" ;;
     *american*dad*)   scp "$filename" "[email protected]:/users/imac/Movies/Series/American\ Dad/" && rm "$filename" ;;
     *) echo "Don't know where to put $filename" ;;
  esac
done
like image 872
fedxc Avatar asked Dec 04 '22 20:12

fedxc


1 Answers

This is where the shell's case statement comes in handy:

#!/bin/bash
cd "$HOME/Downloads"
for filename in *; do
  # this syntax emits the value in lowercase: ${var,,*}  (bash version 4)
  case "${filename,,*}" in
    glee*)    mv "$filename" "$HOME/TVshows/Glee/" ;;
    pokemon*) mv "$filename" "$HOME/TVshows/pokemon/" ;;
    *) echo "don't know where to put $filename";;
  esac
done
like image 66
glenn jackman Avatar answered May 17 '23 17:05

glenn jackman