Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count a pattern inside a phrase?

For example:

/A/B/C/D/

I know that this command:

awk -FS'/' '{print $1}'

Prints the first pattern: A

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But, how can I count the number of ‘/’ inside that phrase? The output will be: 5

>Solution :

You might inform GNU AWK that / is field using FPAT built-in variable and then check number of fields, let file.txt content be

/A/B/C/D/

then

awk 'BEGIN{FPAT="/"}{print NF}' file.txt

gives output

5

(tested in GNU Awk 5.1.0)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading