Match the column heading and print the values of the column using awk

9,979

Solution 1

Create a script for example called script.sh with this:

awk -v COLT=$1 '
        NR==1 {
                for (i=1; i<=NF; i++) {
                        if ($i==COLT) {
                                title=i;
                                print $i;
                        }
                }
        }
        NR>1 {
                if (i=title) {
                        print $i;
                }
        }
' file

Where file is the file with the data in columns.

If you issue script.sh C-8 then the result will be:

C-8
30
21
67

Solution 2

Try with this:

function proj() {
    awk -v c="$1" 'NR==1 {for (i=1; i<=NF; i++) if ($i==c) break} {print $i}' "$2"
}

Use it like:

proj C-8 table.txt

If you expect to pass in column names which are not present in the table you should check that: add i!=NF+1 before {print $i}, otherwise you'll get as many empty lines as the rows of the table.

You can also put it in a separate file instead using a function.

Solution 3

Without awk, you can use the following command:

cut $FILE -f `head -1 $FILE | tr "\t" "\n" | grep -n "^$COLUMNTITLE"'$' | cut -f 1 -d :`

Works only if there is a single column matching the exact $COLUMNTITLE

Share:
9,979

Related videos on Youtube

KumarJohn
Author by

KumarJohn

Updated on September 18, 2022

Comments

  • KumarJohn
    KumarJohn over 1 year

    I have a data in the file in columns. I want to write a script, which displays the data of the column matching the column heading.

    C-1 C-2 C-3 C-4 C-5 C-6 C-7 C-8 C-9
    10  30  35  20  9   65  87  30  29
    40  32  67  78  30  54  24  21  13
    50  43  32  12  43  65  78  67  54
    

    if the user choose to display C-8 column then the out put must be

    C-8
    30
    21
    67
    

    I am not sure how to match the column name and print the output using awk.

    Thanks, KJ

  • KumarJohn
    KumarJohn almost 9 years
    Thanks for the solution, it works perfectly. Can you please explain what "column=${column:(-1)}" is working.
  • jcbermu
    jcbermu almost 9 years
    Takes the last character of variable column
  • jcbermu
    jcbermu almost 9 years
    I made a change to use the *title column` instead of a number
  • jcbermu
    jcbermu almost 9 years
    If there is not maching, it shows nothing. If text on column is like Rollno for example, change variable to_remove on the script.
  • KumarJohn
    KumarJohn almost 9 years
    This is not working, I am getting complete table as the output.
  • jcbermu
    jcbermu almost 9 years
  • jcbermu
    jcbermu almost 9 years
    @KumarJohn Now you can use any name you want.