Extract all email in line using awk

Viewed 263

I am trying to extract all emails of the line with awk. This is what I tried:

echo " test@test.com secondtest@test.com" | awk 'BEGIN{IGNORECASE = 1}{while(match($0,/[^\s@]+@[^\s@]+\.[a-z]{2,4}/, result) !=0 ) { printf "%s\\n",result[0]; $0 = sub(/[^\s@]+@[^\s@]+\.[a-z]{2,4}/,"", $0)}}'

But is doesn't work properly. I am expecting the following output:

test@test.com 
secondtest@test.com
2 Answers

Using OP's regex here and trying to fix OP's attempt here. We need to use [[:space:]] in place of \s in code also no need to use sub here and simply we could go through all fields one by one with for loop and print the matched one(by using if condition in which regex is used, simply if condition satisfies and regex match is TRUE then print that field else do nothing). Written and tested with GNU awk.

echo " test@test.com secondtest@test.com" | 
awk '
{
  for(i=1;i<=NF;i++){
     if($i~/[^[:space:]]+@[^[:space:]]+\.[[:alpha:]]{2,4}/){  print $i  }
  }
}'

Using gnu-awk you can use a custom RS set as one or more whitespaces and use this simpler awk that splits each whitespace delimited string as a separate record:

echo " test@test.com secondtest@test.com" |
awk -v RS='[[:space:]]+' '/^[^@[:blank:]]+@[^[:blank:]]+\.[[:alpha:]]{2,4}$/'
test@test.com
secondtest@test.com
Related