Ask Your Question
2

How can multiple patterns be counted in a file using AWK?

asked 2021-06-28 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-10-29 10:00:00 +0000

huitzilopochtli gravatar image

To count multiple patterns in a file using AWK, you can use the following syntax:

awk '/pattern1/ {count1++} /pattern2/ {count2++} END {print "Pattern 1 count:", count1; print "Pattern 2 count:", count2}' file.txt

In this command, replace pattern1 and pattern2 with the patterns you want to count in the file.txt. The code increments the count variables count1 and count2 every time the respective patterns are found in the file.

The END block in AWK is executed after all the lines are processed. In the END block, we print the count variables, which gives the number of occurrences of pattern1 and pattern2 in the file.

You can extend this command to count more patterns, by adding another pattern check and count variable increment in the same format.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-28 11:00:00 +0000

Seen: 10 times

Last updated: Oct 29 '21