简体   繁体   English

Python 像 Linux grep 一样搜索并打印出整行?

[英]Python to search and print out the whole line just like Linux grep?

Let's use this as example.让我们以此为例。

>>> t = '''Line 1
... Line 2
... Line 3'''
>>> 

re.findall only print out the specific pattern which is similar to Linux grep -o re.findall只打印出类似于 Linux grep -o的特定模式

>>> re.findall('2', t)
['2']
>>> 

Linux grep Linux grep

wolf@linux:~$ echo 'Line 2' | grep 2
Line 2
wolf@linux:~$ 

Linux grep -o Linux grep -o

wolf@linux:~$ echo 'Line 2' | grep 2 -o
2
wolf@linux:~$ 

I know it's possible to print out the whole output, I just can't think the logic at the moment.我知道可以打印出整个 output,我现在想不出逻辑。

Expected Output in Python Python 中的预期 Output

Line 2

If there's better way to do this, please let me know.如果有更好的方法可以做到这一点,请告诉我。

print([l for l in t.splitlines() if "2" in l])

Or, if you want it separated as in grep ,或者,如果您希望它像grep那样分开,

print('\n'.join([l for l in t.splitlines() if "2" in l]))
t = '''Line 1
Line 2
Line 3'''

for line in t.split('\n'):
    if(line.find("2")!=-1):
        print(line)

This should work for your usecase.这应该适用于您的用例。 find() is used to check if a pattern is present in a string find() 用于检查字符串中是否存在模式

Put.* around what you want to find:将.* 放在您要查找的内容周围:

re.findall(r'.*2.*', t)  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM