如果该行以加号开头,则加入该行,而下一行以Solaris开头

时间:2018-08-16 16:46:30

标签: python-3.6

如果该行以加号开头,而下一行以Solaris开头,则加入该行,然后仅将这两行合并为一。

数据如下图所示,只是在寻找想法。

我之所以这样问,是因为数据与我上面显示的模式不一致。

   ++++++++ host01 ++++++++
                              Solaris 10 10/08 s10s_u6wos_07b SPARC
   ++++++++ host02 ++++++++
                              Solaris 10 10/08 s10s_u6wos_07b SPARC    
    ++++++++ host21 ++++++++
    ssh: connect to host host011 port 22: Connection timed out
    ssh: connect to host host012 port 22: Connection timed out

我在下面尝试过,但没有得到任何结果。

#!/grid/common/pkgs/python/v3.6.1/bin/python3
stat = ""
with open("sunfor", mode="r") as f:
    for line in f:
        line = line.strip()
        if stat.startswith("+") and line.endswith("SPARC"):
            print(stat.strip())
            print(line)

甚至尝试过。.

#!/grid/common/pkgs/python/v3.6.1/bin/python3
with open("sunfor", mode="r") as f:
    for line in f:
        line = line.strip()
        if line.startswith("+") and line.startswith("Solaris"):
            print(line)

1 个答案:

答案 0 :(得分:0)

通过将stat设置为它现在可以正确比较的最后一行。 然后使用加号将结果打印为concat

#!/grid/common/pkgs/python/v3.6.1/bin/python3
stat = ""
with open("sunfor", mode="r") as f:
    for line in f:
        line = line.strip()
        if stat.startswith("+") and line.endswith("SPARC"):
            print(stat.strip()+line)
        stat = line

结果

  

++++++++ host01 ++++++++ Solaris 10 10/08 s10s_u6wos_07b SPARC

     

++++++++ host02 ++++++++ Solaris 10 10/08 s10s_u6wos_07b SPARC