awk how to print the last value of a counter?

Viewed 117

I have a file with some lines starting with >

I want to count the number of such lines per file.

awk '{if(/>/){count += 1}{print count}}' file.text
1
1
2
2

Obviously here I just want the last "2". Basically I want awk to print the last value of count. It seems to me that should be easy to accomplish but can't find how.

I know there are solutions such as grep -c that would do the job but I am curious to have the awk version.

Thank you

EDIT: I have tried this

awk '{if(/>/){count += 1}END{print count}}' Scaffold_1_8558356-8558657.fa_transcripts.combined.filtered.fas
awk: cmd. line:1: {if(/>/){count += 1}END{print count}}
awk: cmd. line:1:                     ^ syntax error
2 Answers

With your tried code try following once.

awk '{if(/>/){count += 1}} END{print count+0}' file.text

OR you could shorten above to:

awk '/>/{count++} END{print count+0}' file.text

Beware, you want to

I have a file with some lines starting with > I want to count the number of such lines per file.

but you are asking AWK to check

if(/>/)...

which will be true for > anywhere in line, for example if file.txt content is:

abc > def
ghi > jkl
mno > prs

then

awk '{if(/>/){print $0}}' file.txt

output

abc > def
ghi > jkl
mno > prs

You might limit to detecting only at start of line using ^ for example use '{if(/^>/){print $0}}' to print only lines which starts with >.

(tested in gawk 4.2.1)

Related