2014-09-30 16 views
2

我一直在這個工作了一段時間,我似乎無法破解它。我有一個文件夾中的一些文件正則表達式不工作使用循環來通過文件名

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在爲我不確定這是否會在殼工作,只是堅持與SS和EE所以它是不區分大小寫結束

+0

爲什麼不簡化並在其他所有工作正常時回到複雜的reg-expr。我會在* [Ss] [0-9] [Ee] [0-9]中做'case $ f *)做$ f;的東西。 *)echo $ f didn_t match ;; esac'(或類似的)。你可以'OR'(用'|')char多重測試,例如* [Ss] [0-9] [Ee] [0-9] * | * [Ss] [0-9]中的case $ f [ 0-9] [Ee] [0-9] [0-9] * ...'。祝你好運。 – shellter 2014-09-30 18:37:18

+1

我不認爲'\ d'在shell中是有效的。嘗試使用'[[:digit:]]'(或者像你已經使用過的'[0-9]''的類)。你在OP中的片段中也有一個錯字。你錯過了''$ filename'的引號 – 2014-09-30 18:49:28

+0

沒有任何作品,當我執行這個例子時,沒有任何東西出現。'我嘗試了各種正則表達式組合,沒有任何東西可以工作 – 2014-10-01 00:29:38

回答

0

一些修改:

(1)在表達式中將\d修復爲[0-9]

(2)中的if塊

而且現在的腳本應該工作結束脩復引號"在該行if [[ "$filename =~ $regex ]]

(3)添加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