我需要从文件中找到精确的字符串。假设简单文本文件包含3行文本
SILVERGOLD-A
SILVERGOLD-AMY
SILVERGOLD-ACB
我需要找到精确的字符串"SILVERGOLD-A"
。我正在终端中使用以下命令:
cat text.txt | grep "\bSILVERGOLD-A\b"
而且我只能成功地获得"SILVERGOLD-A"
作为输出。但是,它不能在Python中使用subprocess.POpen
。我的代码如下所示:
cmd1 = ['cat', text.txt]
cmd2 = ['grep', find_string] ==> Where String is find_string = '\'\b' + find_string + '\'\b'
ps = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
grep = subprocess.Popen(cmd2, stdin=ps.stdout, stdout=subprocess.PIPE)
ps.stdout.close()
print("grepout {0}".format(grep.communicate()))
但是我继续得到空的grep结果。有什么线索或帮助吗
若我从字符串中删除\b
,那个么我会得到所有匹配的字符串(甚至是部分匹配)
您可能希望在
find_string
中转义\
,以便它读取'\\b'
。或者,您可以使用r-stringr'\b'
另外,我认为你需要在你的
find_string
中去掉\'
。如果它打算引用正则表达式,我想Popen()
会自动为您引用args。以下doc似乎是相关的:所以,对我来说
cmd2 = ['grep', r'\b' + 'SILVERGOLD-A' + r'\b']
似乎有效。试试这个作为旁注,
grep
如果您提供输入文件,则不需要stdin;i、 例如,您可以将代码简化如下:相关问题 更多 >
编程相关推荐