How to awk files based on coumn name

classic Classic list List threaded Threaded
6 messages Options
Reply | Threaded
Open this post in threaded view
|

How to awk files based on coumn name

shraddha
Hi,

Can anyone help me out to awk a file based on column name.

I have files where the order of the column names changes in the header. And I need to get the data based on column name.

like

File1.txt has

name place location
a       india  hyd
b       china beijing

File2.txt has

place  location name
india   delhi      c

and I need to get the data from column name 'location' from both the files.

 
Reply | Threaded
Open this post in threaded view
|

Re: How to awk files based on coumn name

Guru
Administrator
Can you please show the sample output expected from these 2 files?


Reply | Threaded
Open this post in threaded view
|

Re: How to awk files based on coumn name

shraddha
output i need is

hyd
beijing
Reply | Threaded
Open this post in threaded view
|

Re: How to awk files based on coumn name

Guru
Administrator
$ cat file
name place location
a       india  hyd
b       china beijing

$ awk 'NR==1{for(i=1;i<=NF;i++){if ($i == "location")j=i;}next}{print $j}' file
hyd
beijing
$
Reply | Threaded
Open this post in threaded view
|

Re: How to awk files based on coumn name

shraddha
Thank you. I have tried this and there are some empty columns in the file and bcoz of this I am unable to get the expected output.
The files are something like this

location name place
hyd india
beijing b china

The output I am getting with the above command when Im searching for name is 
india
b
where the Expected Output should be(should give no value if there is no value in the cell under name)

b

Regards,
Shraddha Kakaraparthi


On Wed, Aug 27, 2014 at 10:10 AM, Guru [via The UNIX School Forum] <[hidden email]> wrote:
$ cat file
name place location
a       india  hyd
b       china beijing

$ awk 'NR==1{for(i=1;i<=NF;i++){if ($i == "location")j=i;}next}{print $j}' file
hyd
beijing
$



If you reply to this email, your message will be added to the discussion below:
http://forum.theunixschool.com/How-to-awk-files-based-on-coumn-name-tp174p177.html
To unsubscribe from How to awk files based on coumn name, click here.
NAML

Reply | Threaded
Open this post in threaded view
|

Re: How to awk files based on coumn name

Guru
Administrator
 This can be achieved if the file has a delimiter other than whitespace. In this case, there is no delimiter.