【发布时间】:2017-09-07 14:07:43
【问题描述】:
我在字典中有一堆用于解析信息的搜索字符串。
my_func_dict = {
'index_one': r'pattern1'
'index_two': r'pattern2'
etc
}
然后我使用以下内容来捕获评估和应用我的搜索字符串的路径,它工作正常。
if len(sys.argv) >= 2:
location = sys.argv[1]
else:
location = raw_input("Enter the path to evaluate...>: ")
然后,我迭代字典项以应用搜索命令:
search_cmd = 'grep -h -r'.split()
for name, pattern in my_func_dict.items():
with open('{}.txt'.format(name), 'a') as output:
cmd = search_cmd + [pattern, location]
subprocess.call(cmd, stdout=output)
这适用于少数搜索模式和少数要评估的文件。但在我的情况下,我有许多搜索模式并将它们应用于包含多个文件的文件夹,这些文件包括多种扩展类型:*.txt、*log 等,这需要很长时间。我想先使用find 选项在文件夹路径中仅查找特定文件类型,然后更精确地应用grep 以便更快地获得输出结果。
但以下尝试:
search_cmd = 'find $location -name "*test.txt" -print0 | xargs -0 grep -h -r'.split()
for name, pattern in my_func_dict.items():
with open('{}.txt'.format(name), 'a') as output:
cmd = search_cmd + [pattern, location]
subprocess.call(cmd, stdout=output)
给我一个错误:
find: |: unknown primary or operator
find: |: unknown primary or operator
find: |: unknown primary or operator
find: |: unknown primary or operator
如何实现我的search_cmd 以避免此问题?我需要使用-print0 和xargs -0 作为find 的属性,因为路径中的文件夹名称有空格,例如:/This is the path/for/This Folder。谢谢
【问题讨论】:
-
这不是我非常了解的东西,但您不应该在 search_cmd = ... 行上遇到语法错误吗?
-
更改为:
search_cmd = 'find $location -name "*test.txt" -print0 | xargs -0 grep -h -r'.split(),这个给出了find: |: unknown primary or operator错误。 -
那个有输出重定向而不是管道,但没有什么不同。
-
在使用 dup 中的建议后仍然无法使其工作:
search_cmd = shlex.split("""find $location -name "*test.txt" -print0 | xargs -0 grep -h -r"""),仍然出现以下错误:find: |: unknown primary or operator
标签: python regex grep find associative-array