2015-11-16 159 views
-3

我試圖實現一個簡單的shell程序,顯示文件中包含的法國電話號碼。邏輯或| Unix

這裏是我的基本殼

#!/bin/bash 

#search of phone numbers 

t=(\+ | 00)33[1-9][0-9]{8} 
t2=(\+ | 00)33[1-9][0-9]-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2} 
t3=(\+ | 00)33[1-9][0-9].[0-9]{2}.[0-9]{2}.[0-9]{2}.[0-9]{2} 

grep -e $1 ($t | $t2 | $t3) 

這裏是我的輸入文件:

phone_number.txt

+33143730862 

00335.45.45.45.45 

+332-45-45-45-45 

+334545454554454545 

我不斷收到此錯誤:

./script_exo2.sh: line 5: syntax error near unexpected token `|' 
./script_exo2.sh: line 5: `t=(\+ | 00)33[1-9][0-9]{8}' 
./script_exo2.sh: line 6: syntax error near unexpected token `|' 
./script_exo2.sh: line 6: `t2=(\+ | 00)33[1-9][0-9]-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}' 
./script_exo2.sh: line 7: syntax error near unexpected token `|' 
./script_exo2.sh: line 7: `t3=(\+ | 00)33[1-9][0-9].[0-9]{2}.[0-9]{2}.[0-9]{2}.[0-9]{2}' 
./script_exo2.sh: line 9: syntax error near unexpected token `(' 
./script_exo2.sh: line 9: `grep -e $1 ($t | $t2 | $t3)' 
+10

你可能想要在字符串和變量之間加一些引號。 http://www.shellcheck.net是你的朋友。 – Biffen

+4

OS X上的'bash'與任何你能找到的Linux上的'bash'都一樣。您提供的腳本在任何腳本中都是無效的,因爲它使用shell元字符和控制操作符在需要將它們作爲數據(特別是'(',')','''和空格字符)。 –

+0

'00'不是一個通用的國際通話前綴,但在許多國家都是正確的。這就是爲什麼我們需要普遍的'+'。 – tripleee

回答

3

您的t2t3比您嘗試匹配的樣本多一位數字。此外,您還需要引用的論據,並擺脫那些空間:

#!/bin/sh 
t='(\+|00)33[1-9][0-9]{8}' 
t2='(\+|00)33[1-9]-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}' 
t3='(\+|00)33[1-9]\.[0-9]{2}\.[0-9]{2}\.[0-9]{2}\.[0-9]{2}' 

exec grep -E -e "$t|$t2|$t3" "[email protected]" 
  1. 我用sh代替bash,因爲我們不使用任何bash特性不提供標準的POSIX殼(例如dash)。
  2. 我對tt1t2的定義使用了上面的單引號,並且使用雙引號將它們替換。
  3. 我已經通過-E標誌告訴grep瞭解擴展正則表達式,並且我已將該模式作爲參數-e(「表達式」)標誌設置爲grep
  4. grep進程exec代替shell,因爲沒有理由爲此分支。
  5. 我已經通過了全套的輸入參數"[email protected]"這樣你就可以給額外的選項來grep(如-w-n-o,例如),並選擇是否提供文件或流標準輸入到你的腳本。

還要注意的是,如果你願意接受的.-或沒有分離數字對混合,可以簡化你的三個表達式只有一個:

(\+|00)33[1-9][0-9]([-.]?[0-9]{2}){4} 

和腳本變得

#!/bin/bash 
exec grep -E -e '(\+|00)33[1-9]([-.]?[0-9]{2}){4}' "[email protected]" 

如果需要分隔符匹配,那麼你可以使用一個捕獲組爲:

#!/bin/bash 
exec grep -E -e '(\+|00)33[1-9]([-.]?)[0-9]{2}(\2[0-9]{2}){3}' "[email protected]" 
+0

非常感謝您的幫助。 –