1

I have a pipe-delimited file with an email address in the third column. I need help to create the fourth column out of the domain name from the email address in the third column using awk or sed command.

Input file

TEST|1234|john.doe@gmail.com
TEST|4533|jeffp12@yahoo.com
TEST|9030|indoep13@gmx.com
TEST|0903|ramdpe23@gmail.com

Expected output

TEST|1234|john.doe@gmail.com|gmail.com
TEST|4533|nobody1@yahoo.com|yahoo.com
TEST|9030|mailmejeff@gmx.com|gmx.com
TEST|0903|ramdpe23@gmail.com|gmail.com
1
  • edit your question to tell us: What have you tried? What problem did you experience? – Ed Morton Jul 16 '19 at 13:13
4

Try this,

awk -F '@' '{print $0"|"$NF}' file

TEST|1234|john.doe@gmail.com|gmail.com
TEST|4533|jeffp12@yahoo.com|yahoo.com
TEST|9030|indoep13@gmx.com|gmx.com
TEST|0903|ramdpe23@gmail.com|gmail.com
4
  • Just tried but this did not work. Here is a sample output. |gmail.com.TEST|ohn.doe@gmail.com – Bala Jul 16 '19 at 7:20
  • 1
    @Bala you have DOS line endings, see stackoverflow.com/q/45772525/1745001 – Ed Morton Jul 16 '19 at 13:14
  • Thank you.That's correct I had to run this sed to change the line endings to unix. sed -i 's/\r//g' – Bala Jul 17 '19 at 5:42
  • @Bala you can also use the dos2unix to convert... – Siva Jul 17 '19 at 5:53
0

Using sed:

$ sed 's/@\(.*\)/&|\1/' file
TEST|1234|john.doe@gmail.com|gmail.com
TEST|4533|jeffp12@yahoo.com|yahoo.com
TEST|9030|indoep13@gmx.com|gmx.com
TEST|0903|ramdpe23@gmail.com|gmail.com

This would match the first @ character on each line and capture everything after it with a capture group. The matched text would be replaced by itself followed by the captured text, with a | character in-between.

If your file is a DOS text file (as indicated by some of the comments), then you can handle the conversion to a Unix text file in one and the same command:

$ sed -e 's/[[:cntrl:]]$//' -e 's/@\(.*\)/&|\1/' file
TEST|1234|john.doe@gmail.com|gmail.com
TEST|4533|jeffp12@yahoo.com|yahoo.com
TEST|9030|indoep13@gmx.com|gmx.com
TEST|0903|ramdpe23@gmail.com|gmail.com

The 2nd substitution is the same as before, but the first will remove any control character at the very end of the line (this would remove a carriage return character at the end of each line, if there was one). The output of this last command will be a Unix text document regardless of whether the original file was a DOS or Unix text file.

-1

Tried with below script

for i in `cat o.txt`; do y=`echo $i |awk -F "|" '{print $NF}'| awk -F "@" '{print $NF}'`; echo $i | awk -v y="$y"  '{print $0"|"y}'; done

output

TEST|1234|john.doe@gmail.com|gmail.com
TEST|4533|jeffp12@yahoo.com|yahoo.com
TEST|9030|indoep13@gmx.com|gmx.com
TEST|0903|ramdpe23@gmail.com|gmail.com

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.