Awk - How to print match instead of whole line
I wish to use awk in order to extract email addresses from a log file. I wrote the proper regular expression, however it prints the whole line, while i want it to only print the match (in my case, the email address). Can it be done?
Here is my code: tail -f /var/log/mail.log | awk '/\ to=([^@]+@[^,:]+)/ { print $7 }' ... where $7 is useless for my goal, it only serves as something to print during testing. Please assist. Panos |
Hi,
please provide some sample data. It is hard to guess what is wrong without seeing the input and output. |
Of course.
A standard line from my mail server's log looks like this: Code:
Oct 24 19:20:27 server postfix/pipe[31099]: 236041EA4AC0: to=<g.pavlakis@domain.com>, relay=dovecot, delay=0.81, delays=0.8/0/0/0.01, dsn=2.0.0, status=sent (delivered via dovecot service) Code:
g.pavlakis@domain.com |
Well, you can surely do this with awk. However, how about a sed solution? It is a bit easier in this case since it is RegEx oriented while awk is field oriented. This worked with your sample:
Code:
sed -r 's/.*to=<([^>]*)>.*/\1/' |
Quote:
Will your sed solution allow me to assign the found/matched email address to some variable and call an external script for further processing? I mean, after i find the address, i was thinking that perhaps i could "post" it to some other script for e.g. inserting it in a database or something. Is that possible? |
Quote:
Code:
variable=$(sed -r 's/.*to=<([^>]*)>.*/\1/' filename) |
Lovely.
One thing though.. i run your see code, along with my tail -f (contained in the original one-liner i posted) and it behaves as follows: a) The first time it matches.. yes it prints the email address alone. b) All subsequent times it matches, it prints the complete log line that contains the match, exactly as my faulty awk was doing. Did i miss something? The whole point is that it keeps extracting email addresses as they appear in the log files, in real time. Panos |
Quote:
Code:
variable=$(sed -nr 's/.*to=<([^>]*)>.*/\1/p' filename) |
Sincere thanks.
Problem SOLVED. |
All times are GMT -5. The time now is 06:52 AM. |