目前,我在使用declare -A
的bash中存在限制,以便使用關聯數組並將字符串視爲索引,這是因爲我無法安裝v4.0
環境。作爲一種解決方法,我試圖用Python構建我的腳本。這是我想在Python翻譯代碼:如何使用Python中使用包含在字典中的正則表達式使用Python
declare -A regex
regex[test_one]="line1\|here1"
regex[test_two]="line2\|here2"
regex[test_three]="line3\|here3"
regex[test_four]="line4\|here4"
echo -n "Enter the path to evaluate...> "
read path
for i in "${!regex[@]}"
do
grep -h -r --color=always "${regex["$i"]}" "$path" >> "$i.txt"
done
任何幫助,將大大appreciated.Thanks
編輯注:
這是一段代碼,我目前,謝謝到@Harvey
import sys
import subprocess
regex = {
'test_one': r'line1\|here1',
'test_two': r'line2\|here2',
}
sys.stdin.flush()
path = raw_input("Enter the path to evaluate...> ")
search = "/bin/sh -c \'grep -h -r'.split()"
for name, pattern in regex.items():
with open('{}.txt'.format(name), 'a') as output:
cmd = search + [pattern,path]
subprocess.call(cmd, stdout=output)
不過,我已經在Line 18
以下錯誤:
Traceback (most recent call last):
File "./Script.py", line 18, in <module>
cmd = search + [pattern,path]
TypeError: cannot concatenate 'str' and 'list' objects
你有沒有試過用Python寫這個?分享您的代碼並指定問題。 – Harvey
修復此問題:'「/ bin/sh -c \'grep -h -r'.split()」'。 '.split()'在'「字符串之後。擺脫'/ bin/sh'部分。這是沒有必要的。查看我答案中的最新代碼。它已經過測試。 – Harvey
OK !,我改變了你的建議,它只在傳遞命令行參數時起作用,例如:'./script.py/the/path/to/directory',但是如果我不帶參數運行命令,我會得到以下:'path = sys.argv [1]' 'IndexError:列表索引超出範圍' – raver83