Mac终端搜索并移动名称中不包含模式的文件

时间:2012-10-06 11:12:51

标签: macos shell unix terminal

我用一个程序来翻录无线电音乐。遗憾的是,人们无法将临时文件夹与完成的mp3最终结束的文件夹区分开来。所以我无法将输出文件夹设置为自动添加到iTunes。

我很喜欢编写java和没有经验的shell脚本。

我需要一个脚本,每隔10分钟迭代文件夹中的所有文件,如果它们不以字符串“Track”开头,则将它们移动到不同的位置。所有临时文件都称为“Track ...”,因此它应该只移动完成的文件。任何人都可以帮我一步吗? 谢谢!

2 个答案:

答案 0 :(得分:0)

这是一个示例脚本。在取消注释移动文件的行之前,应正确设置DESTINATION目录。否则,您最终可能会将它们移到某个不受欢迎的地方。

在终端中,cd到下面保存代码段的位置,然后运行以下命令来执行。

准备工作:

  • cd / save / location
  • chmod + x file_mover.sh#使文件可执行

安排工作:

  • crontab -e
  • * / 10 * * * * /path/to/file_mover.sh
  • crontab -l #view list of scheduled jobs

通过一些小的调整,您可以使这个接受CLI选项。

#!/bin/bash 


# files to skip
REGEX='^TRACK'

# location to move the files
DESTINATION=/tmp/mydir

# directory to read from 
# PWD is the working directory
TARGET=${PWD}

# make the directory(ies) if it doesn't exists
if [ ! -f ${DESTINATION} ]; then
    mkdir -p ${DESTINATION}
fi

# get the collection of files in the 
for FILE in $( ls ${TARGET} )
do
    # if the current file does not begin with TRACK, move it
    if [[ ! ${FILE} =~ ${REGEX} ]]; then

        echo ${FILE}

        # SET THE DESTINATION DIRECTORY BEFORE UNCOMMENTING THE LINE BELOW

        # if [ -f ${FILE} ]; then # uncomment if you want to 
        # ensure it's a file and not a directory     
              # mv ${FILE} ${DESTINATION} # move the file 
        # fi # uncomment to ensure it's a file (end if)
    fi
done

答案 1 :(得分:0)

使用EDITOR=nano crontab -e编辑crontab并添加如下所示的行:

*/10 * * * * shopt -s extglob; mv ~/Music/Temp/!(Track)*.mp3 ~/Music/iTunes/iTunes\ Media/Automatically\ Add\ to\ iTunes.localized/

shopt -s extglob添加了对!()的支持。请参阅/usr/share/doc/bash/bash.html