0

I am trying to print only e-mail addresses from a file, file format is as follows:

{"12":"34","email":"johnsmith@gmail.com","firstname":"john","lastname":"smith","text":"0","sig":"js","..":"2017-08-23"}

How can I just extract using awk -F? So I can use awk -F'"' '{print $8}' but the 8th column may not always be the e-mail address.

Is there a way to use awk -F WITH a regular expression of '@'? Or print all texts in the delimiter in separate lines then pipe it to | grep '@'

Thanks

  • If awk isn't a strict requirement, you could write a small script using language which includes a json parser (such as python). – sebasth Aug 23 '17 at 11:22
  • Better use jq, which will permit you to get the value of attribute "email" – Romeo Ninov Aug 23 '17 at 11:41
0

This is an awk way.

awk -v RS=\" '/@/' infile.txt 

The above is correct when you have quoted fields, else you should have RS with multiple RecordSeperators. like RS='[[:blank:]]*:' per your sample in your comment.

  • I get 12:34 email:johnsmith@gmail.com firstname:john lastname:smith text:0 sig:js ..:2017-08-23 with this :-( – garethTheRed Aug 23 '17 at 11:52
  • so where is the quotes there you have in your shared sample in body of your question? if no quotes change RS to RS='[[:blank:]]*:' to get it to work, also I don't suggest to use awk where there is correct jq tool for that – αғsнιη Aug 23 '17 at 11:57
1

jq is a proper tool for parsing/manipulating json data:

jq '.email' jsonfile

The output:

"johnsmith@gmail.com"
  • Add - r to be rid of the quotes. – Kusalananda Aug 23 '17 at 12:10
  • @Kusalananda, you shouldn't decide instead of OP. If the OP will mention about that requirement - it'll be added – RomanPerekhrest Aug 23 '17 at 12:19
  • Sorry, my intention was to mean "if you want to be rid of the quotes (in the output)", not a critique on the answer as such. jq is definitely the correct solution here. – Kusalananda Aug 23 '17 at 12:22
  • jq is only the correct answer to the question: How can I print a specific field. It is not the answer to this question, which specifically asks how it is done using awk. – garethTheRed Aug 23 '17 at 12:24
  • @garethTheRed, even if the question is "How can I just extract using awk -F from JSON". - using awk for json is a bad practice, fragile solution and a bad advice for the future – RomanPerekhrest Aug 23 '17 at 12:28
0

The reg-ex may need tweaking to be fully compliant with RFC 5322, but as a starter, try:

awk '{match($0,"[a-zA-z0-9._%+-]+@[a-zA-z0-9._%+-]",a)}END{print a[0]}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.