Search code examples
awk

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

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)