Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for a column by name in awk

Tags:

shell

unix

awk

I have a file that has many columns. Let us say "Employee_number" "Employee_name" "Salary". I want to display all entries in a column by giving all or part of the column name. For example if my input "name" I want all the employee names printed. Is it possible to do this in a simple manner using awk? Thanks

like image 362
user2260271 Avatar asked Mar 24 '23 09:03

user2260271


1 Answers

Given a script getcol.awk as follows:

BEGIN {
    colname = ARGV[1]
    ARGV[1] = ""
    getline
    for (i = 1; i <= NF; i++) {
        if ($i ~ colname) {
            break;
        }
    }
    if (i > NF) exit
}

{print $i}

... and the input file test.txt:

apple   banana  candy   deer    elephant
A   B   C   D   E
A   B   C   D   E
A   B   C   D   E
A   B   C   D   E
A   B   C   D   E
A   B   C   D   E
A   B   C   D   E

... the command:

$ awk -f getcol.awk b <test.txt

... gives the following output:

B
B
B
B
B
B
B

Note that the output text does not include the first line of the test file, which is treated as a header.

like image 183
Simon Avatar answered Mar 31 '23 17:03

Simon