Regex不使用循环来浏览文件名

时间:2014-09-30 18:28:31

标签: regex shell

我已经在这方面工作了一段时间,我似乎无法破解它。我在文件夹中有一些文件

testing.test.S09E01.720p.HDTV.x264-TWIST 
dmscript.sh

我有脚本在那里测试它,然后我设置了下载管理器,以便在下载一集后运行。

该脚本具有以下代码。

#!/bin/sh
#THIS SCRIPT WILL DETERMINE TV SHOWS AND EPISODES AND MOVE THEM TO THE CORRECT
#FOLDER WHICH WILL ALLOW EITHER SICKBEARD OR COUCHPOTATO TO RENAME AND MOVE THEM

    regex="([Ss]?([0-9]{1,2})[-|.]?[x|Ee|]?(\d{2})|(0?\d{1})(\d{2}))"

    #where the tv shows will be copied to
    tvdir="/volume1/public/NZB/Complete/tv/processed/"

    #this was a debug variable to allow me to see where the code fails
    num="1"

    #will change the * to full path of folder later, for now this works because script is running from
    #inside folder
    for filename in *
    do
            if [[ "$filename =~ $regex ]]
            then
            #display the current filename and the variable number
            echo "$filename $num"
            #commented on the following code so when the script works I will just uncomment
            #mv $filename $tvdir
            #change variable to 2, this is to see whether the if test will fail and skip the file
            #that doesn't conform to the regex
            num="2"
            else
            echo "nothing of use"

    done

然而,一旦我运行代码,我就会得到这个

testing.test.S09E01.720p.HDTV.x264-TWIST 1
dmscript.sh 2

显然出现了问题,因为我只想让它显示上面列表中的第一个并忽略另一个。

我从http://regex101.com/r/qZ2eO9/1得到了正则表达式规则,我最后忽略了/ gim,因为我不确定这是否可以在shell中工作,只是坚持使用Ss和Ee所以它不区分大小写< / p>

1 个答案:

答案 0 :(得分:0)

一些修改:

(1)将\d修复为表达式中的[0-9]

(2)修正第"

中的引号if [[ "$filename =~ $regex ]]

(3)在if块

的末尾添加fi

现在脚本应该可以工作。

regex="([Ss]?([0-9]{1,2})[-|.]?[x|Ee|]?([0-9]{2})|(0?[0-9]{1})([0-9]{2}))"

#where the tv shows will be copied to
tvdir="/volume1/public/NZB/Complete/tv/processed/"

#this was a debug variable to allow me to see where the code fails
num="1"

#will change the * to full path of folder later, for now this works because script is running from
#inside folder
for filename in *
do  
        if [[ $filename =~ $regex ]]
        then
            #display the current filename and the variable number
            echo "$filename $num"
            #commented on the following code so when the script works I will just uncomment
            #mv $filename $tvdir
            #change variable to 2, this is to see whether the if test will fail and skip the file
            #that doesn't conform to the regex
            num="2"
        else
            echo "nothing of use"
        fi  
done