0

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

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
  • Thanks for the solution, it works perfectly. Can you please explain what "column=${column:(-1)}" is working. – KumarJohn Jun 17 '15 at 11:15
  • Takes the last character of variable column – jcbermu Jun 17 '15 at 11:18
  • I made a change to use the *title column` instead of a number – jcbermu Jun 17 '15 at 11:19
  • This works fine if the column numbers are matching what if the column numbers does not match and column name are some text like name, Rollno, this script will not work in that case. – KumarJohn Jun 17 '15 at 11:26
  • If there is not maching, it shows nothing. If text on column is like Rollno for example, change variable to_remove on the script. – jcbermu Jun 17 '15 at 11:37
1

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

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.