SH脚本根据文件名将文件从一个目录移动到另一个目录

时间:2011-09-27 18:17:53

标签: bash shell

我正在尝试编写一个sh脚本,该脚本将在我的一个下载完成后运行。

它应该在〜/ Downloads上查找特定的文件名,并根据文件名将其移动到不同的目录。

即。我已经下载了Glee的最后一集,文件名为:

glee_some_trash_files_always_have.mkv

应移至

~/TVshows/Glee/

这是我能够做到的:

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

我的方法是否正确?请注意我是新来的。

提前致谢。

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

编辑:这是我的剧本,我希望其他人能发现它很有用:

#!/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" "imac@imac.local:/users/imac/Desktop/" && rm "$filename" ;;
     *american*dad*)   scp "$filename" "imac@imac.local:/users/imac/Movies/Series/American\ Dad/" && rm "$filename" ;;
     *) echo "Don't know where to put $filename" ;;
  esac
done

3 个答案:

答案 0 :(得分:7)

这是shell的case语句派上用场的地方:

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

答案 1 :(得分:3)

这是我的串行排序脚本。

#!/bin/bash

PATH_FROM=/your/download/dir
PATH_TO=/path/serial/directory

cd $PATH_FROM
ls -1 *{mkv,avi,srt,mp4} | sed -e 's/\.[s|S][0-9].*$//g' | uniq | while read -r serial
do
    folder=$(echo $serial | tr A-Z a-z) folder=${folder/the./}
    folder=`echo ${folder//_/.}`
    folder=`echo ${folder//./ }`

    folder=( $folder )
    folder=`echo "${folder[@]^}"`

    ls -1 ${serial// /.}.* | sed -e 's/'$serial'\.[s|S]//g' | sed -e 's/\..*$//g' | uniq | while read -r s
    do
        season=s$(echo "$s" | sed -e 's/[e|E].*$//g' | sed -e 's/^0//g')
        mkdir -p "$PATH_TO/$folder/$season"
        mv -f $serial.?$s* "$PATH_TO/$folder/$season/"
        log=`date +"[%d/%m/%Y %X]"`
        echo $log" "$serial" success sync with "$PATH_TO"/"$folder"/"$season >> /path/to/logfiledir/log.txt
    done
done

答案 2 :(得分:1)

mv命令可以一次移动多个文件。最后一个参数被视为目录名称。尾随/很重要;如果有一个匹配的文件名,并且目标目录不存在(例如,因为你拼写错误),它会将其创建为文件。

mv ~/Downloads/*glee* ~/TVshows/Glee/
mv ~/Downloads/*pokemon* ~/TVshows/pokemon/