0

I have a file with the following input data:

Sample1

Feature 1
A
B
C
D
Feature 2
E
F
G

Sample2:

Feature 1
H
I
Feature 2
L
O
P

And I would like to have the following output:

Sample1
Feature 1: 4
Feature 2: 3
Sample2
Feature 1: 2
Feature 2: 3

So basically I'm trying to count how many elements are in each feature, and for each sample separately

I tried using the following command:

awk '{if(/^\Feature/){n=$0;}else{l[n]++}}END{for(n in l){print n" : "l[n]}}' inputfile > outputfile

But it basically gave me the following output (it counted all the features for all samples)

Feature 1: 6
Feature 2: 6

Can somebody please help me modify this command or suggest another one?

0

file summarize.awk:

function print_feature() {
    if (feature) print feature ": " n
    n = 0
    feature = ""
}
NF == 0 {                 # empty line. 
    print_feature()         # print the feature summary
    in_feature = 0          # we are no longer counting elements
    next                    # do not print the empty line
}
$1 == "Feature" {         # a new feature
    print_feature()         # print the previous feature summary
    feature = $0            # save this as the new feature
    in_feature = 1          # indicate we are counting elements
    next                    # do not print ... yet
}
{
    if (in_feature) 
        n++                 # count this element
    else                    # or
        print               # print (e.g. "Sample")
}
END {
    print_feature()         # if there is no trailing blank line, print the current feature
}

Then

$ awk -f summarize.awk file
Sample1
Feature 1: 4
Feature 2: 3
Sample2:
Feature 1: 2
Feature 2: 3

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.