带转义字符的grep

2024-10-03 09:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从文件中找到精确的字符串。假设简单文本文件包含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,那个么我会得到所有匹配的字符串(甚至是部分匹配)


Tags: 字符串texttxtstringstdoutfindgrepcat
1条回答
网友
1楼 · 发布于 2024-10-03 09:20:09

您可能希望在find_string中转义\,以便它读取'\\b'。或者,您可以使用r-string r'\b'

另外,我认为你需要在你的find_string中去掉\'。如果它打算引用正则表达式,我想Popen()会自动为您引用args。以下doc似乎是相关的:

['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]

... arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements.

所以,对我来说cmd2 = ['grep', r'\b' + 'SILVERGOLD-A' + r'\b'] 似乎有效。试试这个

作为旁注,grep如果您提供输入文件,则不需要stdin;i、 例如,您可以将代码简化如下:

import subprocess

cmd2 = ['grep', r'\b' + 'SILVERGOLD-A' + r'\b', 'text.txt']
grep = subprocess.Popen(cmd2, stdout=subprocess.PIPE)
print("grepout {0}".format(grep.communicate()))

相关问题 更多 >