xav
xav

Reputation: 411

how to select a part of the text from a log and add it to the beginning?

please can someone clarify to me what would be the best way to take some text from a log line and insert it in front of the line in python.

Ex. Input

<02>Jan  1 00:12:08 15.27.05.42 1,2017/09/07 00:12:08,......

Output

15.27.05.42,<02>Jan  1 00:12:08 15.27.05.42 1,2017/09/07 00:12:08,......

many thanks

Upvotes: 0

Views: 57

Answers (3)

You should first split text with .split(" ") then you your log file will converted to list then you can use log_elements[index]+log to concate them together.

Upvotes: 0

Marco Milanesio
Marco Milanesio

Reputation: 100

You can use the re module. If the pattern you want to prepend is unique, then it will be something like:

import re
in_ = "<02>Jan  1 00:12:08 15.27.05.42 1,2017/09/07 00:12:08"
pattern = re.compile(r'\d+\.\d+\.\d+\.\d+')
res = re.search(pattern, in_)
if res:
    out_ = "{},{}".format(res.group(), in_)

# '15.27.05.42,<02>Jan  1 00:12:08 15.27.05.42 1,2017/09/07 00:12:08'

Upvotes: 2

Łukasz Szczesiak
Łukasz Szczesiak

Reputation: 214

For 2 strings to connect "+" operator is good enough, but for 3 or more parts strings I recomend using join() method:

log = "02>Jan  1 00:12:08 15.27.05.42 1,2017/09/07 00:12:08"

log = "5.27.05.42," + log

or

log = "".join("5.27.05.42," + log)

About exporting log into string there are many methods, all depends on what form and where you have wrriten log.

Also as @RomanPerekhrest mentions, it is unclear what you want to put before log, if it is something inside log, you will have to use regular expressions.

Upvotes: 0

Related Questions