【问题标题】:Combine grep with and & or logic结合 grep 与 and & or 逻辑
【发布时间】:2016-04-25 10:06:31
【问题描述】:

我正在尝试将以下用 python 编写的代码转换为使用 cat | grep 而不是打开文件。

原代码:

LOG_NAME="/raft/log/{}{}{}_{}_Rx_flow.log".format(NTIME.tm_year,str(NTIME.tm_mon).zfill(2),str(NTIME.tm_mday).zfill(2),str(NTIME.tm_hour).zfill(2))
print time.strftime("%Y/%m/%d %H:%M:%S") + " Log file name, RX restart, is: " + LOG_NAME
print time.strftime("%Y/%m/%d %H:%M:%S") + " ERRTIMEMIN value: " + ERRTIMEMIN + " RXRESTART message value: " + RXRESTART

LINK_LOG_FILE = open(LOG_NAME, "r")
ISRXRESTART=0
for REPline in LINK_LOG_FILE:
  ***if RXRESTART in REPline and (ERRTIMEMIN in REPline or ERRTIMEMIN1 in REPline) and ISRXRESTART==0:***
     #Link restarted - correct behaviour.
     print time.strftime("%Y/%m/%d %H:%M:%S") + " RX restarted - This is correct behaviour"
     ISRXRESTART=1

我必须删除打开文件的行,并将下面带有 *** *** 的行更改为带有 cat 和 grep 的内容 例如:

os.popen("sshpass -p  ssh root@"+self.ipaddr+" cat "+LOG_NAME+"  | egrep `"+device_start+" "+ERRTIMEMIN+`").read().strip()

但我不知道如何在同一个 grep 中组合 or & and

【问题讨论】:

标签: python bash grep


【解决方案1】:

“OR”可以通过简单地一次grep多个模式来模拟:

egrep -E 'thing1|thing2' <file.txt

-E 告诉 egrep 使用扩展的正则表达式。

据我所知,grep 中没有“AND”运算符,但同样可以通过 grep 来模拟正向和反向模式。

egrep -E 'thing1.*thing2|thing2.*thing1' <file.txt

使用-v 表示“不”。

egrep -E 'thing1' <file.txt | egrep -v 'thing2'

这将找到所有带有“thing1”的东西,然后只抓取没有“thing2”的东西。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2017-08-05
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多