Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print the digit number of column in awk

Suppose this file:

col1    |       |       |       |       |       |       col2    -       -       -       -       col3
this    |       |       |       |       |       |       is      -       -       -       -       good
that    |       |       |       |       |       |       not     -       -       -       -       bad

I want to print only col1 and col2 for example, but as I learnt up to now from awk, I use this by counting manually from col1 as $1 to col2 as $8:

awk '{print $1, $8}' file

The expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

col1    |       |       |       |       |       |       col2    -       -       -       -       col3
1       2       3       4       5       6       8       8       9       10      11      12      13

I mean to use head -1 file | awk SOMETHING to print only the first line and then print the number of each header has.

I mean I use an awk command to check the column number, then I use my awk '{print $1, $8}' command better and without counting manually each column number.

I googled and there were some NFR which don’t seem to solve my problem.

>Solution :

You want the first line only, so you can use NR==1 to only run the block at the first line. You also need to remember the number of records on that line so I’ll save that in the variable fields below.

awk 'NR==1 {
  fields=NF;
  for(i = 1; i <= NF; ++i) printf("%-7s ", $i);
  printf("\n"); 
}
END {
  for(i=1; i <= fields; ++i) printf("%-7s ", i);
  printf("\n");
}' file

The END block is executed when processing file is done.

  • printf("%-7s ", $i); – This prints the value in the i:th column
  • printf("%-7s ", i); – This prints the column number itself
  • - in -7s makes it left justified
  • 7 in -7s makes it take up 7 chars

Output with your input:

col1    |       |       |       |       |       |       col2    -       -       -       -       col3
1       2       3       4       5       6       7       8       9       10      11      12      13
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading