【问题标题】:Mac Terminal search and move files not containing pattern in nameMac 终端搜索和移动名称中不包含模式的文件
【发布时间】:2012-09-27 09:04:04
【问题描述】:

我使用一个程序来翻录广播音乐。可悲的是,不能将临时文件夹与完成的 mp3 稍后结束的文件夹分开。所以我无法将输出文件夹设置为自动添加到 iTunes。

我可以编写 java 代码,但没有使用 shell 脚本的经验。

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

【问题讨论】:

    标签: macos shell unix terminal


    【解决方案1】:

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

    在终端中,cd到下面保存sn-p的位置,运行以下命令执行。

    准备工作:

    • cd /保存/位置
    • chmod +x file_mover.sh # 使文件可执行

    安排工作:

    • crontab -e
    • */10 * * * * /path/to/file_mover.sh
    • crontab -l #查看计划任务列表

    通过一些小的调整,您可以使其接受 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
    

    【讨论】:

      【解决方案2】:

      使用 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

      【讨论】:

      • 强烈建议:将脚本放入$HOME/bin 的文件中(假设是autoimportmp3),然后从crontab 运行该脚本。保持 crontab 中的条目简短(*/10 * * * * $HOME/bin/autoimportmp3);将辛勤工作投入到它运行的脚本中。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      相关资源
      最近更新 更多