Saturday, April 12, 2008

Print a column using sed


$ cat emails.out
user1@hotmail.com
user2@gmail.com
user3@yahoo.com
user4@rediffmail.com
user5@aolmail.com

Required Output:
-----------------

hotmail
gmail
yahoo
rediffmail
aolmail

Solutions:
Using 2 FS with awk
$ awk 'BEGIN{FS="[@,.]"} {print $2}' emails.out

sed solution:
$ sed 's_\(.*\)@\(.*\)\.\(.*\)_\2_' emails.out


Using cut will be a two way process in this case
$ cut -d@ -f2 emails.out | cut -d. -f1

Similarly, if we do not use two FS in the above awk code, we would need a two way process like this
$ awk -F@ '{print $2}' emails.out | awk -F. '{print $1}'


So to print the UserName($1),SHELL(last field),homedir(6th field) of /etc/passwd file, the sed solution would be:

$ sed 's_\(.*\):\(.*\):\(.*\):\(.*\):\(.*\):\(.*\):\(.*\)_\1,\7,\6_' /etc/passwd

And the awk solution is:

$ awk 'BEGIN {FS=":"; OFS=","; print "UserName","SHELL","homedir"} {print $1,$NF,$6}' /etc/passwd

No comments:

© Jadu Saikia www.UNIXCL.com