User2939
User2939

Reputation: 165

How to remove part of every line in a file?

I am trying to print few a log file but I want to eliminate first part of every line in the log file. For example:

[2018-07-10 15:04:11] USER INPUT "hello"
[2018-07-10 15:04:12] SYSTEM RESPONSE: "Hello! How are you doing today"
[2018-07-10 15:04:42] USER INPUT "I am doing good thank you"
[2018-07-10 15:04:42] SYSTEM RESPONSE: "Good to know"

I just want the

USER INPUT "hello"
SYSTEM RESPONSE: "Hello! How are you doing today"
USER INPUT "I am doing good thank you"
SYSTEM RESPONSE: "Good to know"

Current code:

import os
location = '/Users/user 1/Desktop/'

f = open(os.path.join(location, 'xvp.log'), "r")

print(f.read())

Upvotes: 2

Views: 88

Answers (3)

Sushant
Sushant

Reputation: 3669

My regex is not so good so inputs welcomed. You could solve this problem by using a regex -

^[[]\d{4}[-]\d{2}[-]\d{2}[ ]\d{2}[:]\d{2}[:]\d{2}[]][ ]

Why have I used ^? So that it starts matching from the start of your string and doesn't match a [ in the middle of the string, then match the whole pattern. Now you could use python's re module like -

import re
catcher = u'^[[]\d{4}[-]\d{2}[-]\d{2}[ ]\d{2}[:]\d{2}[:]\d{2}[]][ ]'
your_string = '[2018-07-10 15:04:12] SYSTEM RESPONSE: "Hello! How are you doing today"'
your_string = re.sub(catcher, '', your_string)
# re.sub will replace all the matches
# It takes - (regex_pattern, replace_the_matches_with, your_match_string) 

Output - SYSTEM RESPONSE: "Hello! How are you doing today"

Upvotes: 0

Mint
Mint

Reputation: 1059

Here's a start

import os
location = '/Users/user 1/Desktop/'

f = open(os.path.join(location, 'xvp.log'), "w+")

for line in f.readlines():
    index_ = line.index(']') + 2
    new_line = line[index_:]
    # TODO: save the new_line to the file

f.close()

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195553

You can try re module:

s = '''[2018-07-10 15:04:11] USER INPUT "hello"
[2018-07-10 15:04:12] SYSTEM RESPONSE: "Hello! How are you doing today"
[2018-07-10 15:04:42] USER INPUT "I am doing good thank you"
[2018-07-10 15:04:42] SYSTEM RESPONSE: "Good to know"'''

import re

print(re.sub(r'\[(.*?)\]\s+', '', s))

prints:

USER INPUT "hello"
SYSTEM RESPONSE: "Hello! How are you doing today"
USER INPUT "I am doing good thank you"
SYSTEM RESPONSE: "Good to know"

To connect it to your code just read the string from file to variable and use the re.sub function.

Upvotes: 0

Related Questions