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|[email protected]
TEST|4533|[email protected]
TEST|9030|[email protected]
TEST|0903|[email protected]

Expected output

TEST|1234|[email protected]|gmail.com
TEST|4533|[email protected]|yahoo.com
TEST|9030|[email protected]|gmx.com
TEST|0903|[email protected]|gmail.com
1
  • edit your question to tell us: What have you tried? What problem did you experience?
    – Ed Morton
    Jul 16, 2019 at 13:13

3 Answers 3

4

Try this,

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

TEST|1234|[email protected]|gmail.com
TEST|4533|[email protected]|yahoo.com
TEST|9030|[email protected]|gmx.com
TEST|0903|[email protected]|gmail.com
4
  • Just tried but this did not work. Here is a sample output. |gmail.com.TEST|[email protected]
    – Bala
    Jul 16, 2019 at 7:20
  • 1
    @Bala you have DOS line endings, see stackoverflow.com/q/45772525/1745001
    – Ed Morton
    Jul 16, 2019 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, 2019 at 5:42
  • @Bala you can also use the dos2unix to convert...
    – Siva
    Jul 17, 2019 at 5:53
0

Using sed:

$ sed 's/@\(.*\)/&|\1/' file
TEST|1234|[email protected]|gmail.com
TEST|4533|[email protected]|yahoo.com
TEST|9030|[email protected]|gmx.com
TEST|0903|[email protected]|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|[email protected]|gmail.com
TEST|4533|[email protected]|yahoo.com
TEST|9030|[email protected]|gmx.com
TEST|0903|[email protected]|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|[email protected]|gmail.com
TEST|4533|[email protected]|yahoo.com
TEST|9030|[email protected]|gmx.com
TEST|0903|[email protected]|gmail.com

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .