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:
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 columnprintf("%-7s ", i);– This prints the column number itself-in-7smakes it left justified7in-7smakes 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