Raja G
Raja G

Reputation: 6633

How to get total column from awk

I am testing awk and got this thought .So we know that

raja@badfox:~/Desktop/trails$ cat num.txt
1   2   3   4
1   2   3   4
4   1   2   31
raja@badfox:~/Desktop/trails$ awk '{ if ($1 == '4') print $0}' num.txt
4   1   2   31
raja@badfox:~/Desktop/trails$ 

so the command going to check for 4 at 1st column in filename num.txt .

So now i want output as there is a 4 at column 4 also and for example if i have 100 column of information and i want get the output as how many columns i have with the term i am searching .

I mean from the above example i want column 4 and column 1 as the output and i am searching for 4 .

Upvotes: 0

Views: 336

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753930

If you are trying to find the rows which contain your search item (in this case, the value 4), and you want a count of how many such values appear in the row (as well as the row's data), then you need something like:

awk '{ count=0
       for (i = 1; i <= NF; i++) if ($i == 4) count++
       if (count) print $i ": " $0
     }'

That doesn't quite fit onto one SO line.

If you merely want to identify which columns contain the search value, then you can use:

awk '{ for (i = 1; i <= NF; i++) if ($i == 4) column[i] = 1 }
     END { for (i in column) print i }'

This sets the (associative) array element column[i] to 1 for each column that contains the search value, 4. The loop at the end prints the column numbers that contain 4 in an indeterminate (not sorted) order. GNU awk includes sort functions (asort, asorti); POSIX awk does not. If sorted order is crucial, then consider:

awk 'BEGIN { max = 0 }
           { for (i = 1; i <= NF; i++) if ($i == 4) { column[i] = 1; if (i > max) max = i } }
     END   { for (i = 1; i <= max; i++) if (column[i] == 1) print i }'

Upvotes: 2

rahmu
rahmu

Reputation: 5878

You are looking for the NF variable. It's the number of fields in the line.

Here's an example of how to use it:

{
    if (NF == 8) {
        print $3, $8;
    } else if (NF == 9) {
        print $3, $9;
    } 
}

Or inside a loop:

# This will print the line if any field has the value 4
for (i=1; i<=NF; i++) {
    if ($i == 4)
        print $0
}

Upvotes: 1

Related Questions