1

I have the following data in a file:

Neighbor        V          TblVer  InQ OutQ Up/Down  State/PfxRcd
10.230.2.91     4          136041    0    0 35w6d        1178
CHN_RAY_901_1AC_CASR903R004#   exit

Neighbor        V          TblVer  InQ OutQ Up/Down  State/PfxRcd
10.229.5.239    4          890585    0    0 7w5d         1177
10.229.6.239    4          890585    0    0 7w5d         1173
CHN_MAR_905_1AC_CASR903R066#   exit

10.229.30.110

I have to remove the lines starting from CHN and have the output like:

Neighbor        V          TblVer  InQ OutQ Up/Down  State/PfxRcd
10.230.2.91     4          136041    0    0 35w6d        1178

Neighbor        V          TblVer  InQ OutQ Up/Down  State/PfxRcd
10.229.5.239    4          890585    0    0 7w5d         1177
10.229.6.239    4          890585    0    0 7w5d         1173

10.229.30.110

I have tried:

b = ' '.join(word for word in content.split(' ') if not word.startswith('CHN'))

where content is my data I want to remove CHN from, but it's not working.

Could you suggest ways to achieve this. Can this be done without using regular expressions? Thanks in advance.

1
  • Try content.splitlines() instead of content.split(' '). Commented Aug 12, 2016 at 16:06

3 Answers 3

2

It may be easier to work with individual lines instead of whole file contents:

with open("file") as f:
    lines = [line for line in f if not line.startswith("CHN")]
    filtered = "".join(lines)
Sign up to request clarification or add additional context in comments.

Comments

2
file = """    Neighbor        V          TblVer  InQ OutQ Up/Down  State/PfxRcd
10.230.2.91     4          136041    0    0 35w6d        1178
CHN_RAY_901_1AC_CASR903R004#   exit

Neighbor        V          TblVer  InQ OutQ Up/Down  State/PfxRcd
10.229.5.239    4          890585    0    0 7w5d         1177
10.229.6.239    4          890585    0    0 7w5d         1173
CHN_MAR_905_1AC_CASR903R066#   exit

10.229.30.110
"""

output = [line for line in file.splitlines() if not line.startswith('CHN')]
print "\n".join(output)

Comments

1
for line in file:
  if not line[0:3] == "CHN":
    write_line
  else:
    remove_line

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.