1

I want to fetch the date from the standard vsftp log file, the file is as below:

Fri Sep  1 15:43:46 2017 1 ::ffff:172.18.1.168 14848 /IT_inventory.xls b _ i r user01 ftp 0 * c

I tried to use regex:

#!/usr/bin/python
import re
    with open("/var/log/xferlog") as log:
        for line in log:
            pattern = re.compile(r'(\w+) (\w+)')
            match = pattern.search(line)
            print match.group(1)
            print match.group(2)

The code can fetch day and month ( group(1) = Fri, group(2) = Sep ) correctly.

But I want to fetch the date(1), so I change the pattern:

pattern = re.compile(r'(\w+) (\w+) (\d+)')
        match = pattern.search(line)
        print match.group(1)
        print match.group(2)
        print match.group(3)

But the output change to 46, 2017, 1 ( group(1) = 46, group(2) = 2017, group(3) = 1 )

If I set up line manually.

line = "Fri Sep 1 15:43:46 2017 1 ::ffff:172.18.1.168 14848 /IT_inventory.xls b _ i r user01 ftp 0 * c"

pattern = re.compile(r'(\w+) (\w+) (\d+)')
match = pattern.search(line)
print match.group(1)
print match.group(2)
print match.group(3)

Then I can get what I want.

group(1)=Fri, group(2)=Sep, group(3)=1

Can anyone explain it to me?

1 Answer 1

2

You can try this:

import re

s = "Fri Sep  1 15:43:46 2017 1 ::ffff:172.18.1.168 14848 /IT_inventory.xls b _ i r user01 ftp 0 * c"

data = re.findall("^\w+\s\w+", s)[0].split()

Output:

['Fri', 'Sep']
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your solution! It worked. But I am still very curious. Do you know why I will get the wired result if I read the file by syntax "with"?

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.