welcome to the Ubuntu-Linux-OSS blog

Welcome to the Ubuntu-Linux-OSS blog. This blog is authored by Chad Mairn, Alex Bawell, Michael Perfeito, and Todd McBride. Our goal is to use the ideas and references recorded in this blog to improve our own use of this software and to contribute to the community of users utilizing open source applications and operating systems.

Tuesday, September 11, 2012

awk -F and two different separators

We had values in the /etc/passwd file that were separate by a colon : and then some separated by a comma , . I wanted to use awk to print the values from a field that was separated by a common and then a colon.

I ended up with this to make it happen:

# awk -F : '{print $field#}' | awk -F , '{print $field#}'

The first part grabs the colon separated field number you replace the pound sign with. Then the part after the pipe grabs the comma separated field you replace the pound sign with inside of the part extracted in the first part. I don't feel like I've explained that very well, so here is another way of looking at it:

from /etc/passwd
102:108:username:group:home directory:location,phone number:start date

In order to get the phone number but tell awk to stop printing there and not also print start date, you have to tell it to:
# awk -F : '{print $6}' | awk -F , '{print $2}'

First part tells it to recognize the colon delimiter and it grabs "location,phone number" values. Then the next part tells it that you only want the "phone number" value.

No comments:

Post a Comment