To find number of occurrences of a word taken as input from command line in unix

后端 未结 3 1647
孤城傲影
孤城傲影 2021-01-27 18:08

For the file file1.txt which contains

Apple fruit Apple tree
Tree AApple AApklle Apple apple
TREE
Apple

I want to find number of o

相关标签:
3条回答
  • 2021-01-27 18:34

    With GNU awk for multi-char RS:

    $ awk -v RS='\\<Apple\\>' 'END{print (NR ? NR-1 : 0)}' file
    4
    

    or with a shell variable:

    $ tofind='Apple'
    $ awk -v RS='\\<'"$tofind"'\\>' 'END{print (NR ? NR-1 : 0)}' file
    4
    
    0 讨论(0)
  • 2021-01-27 18:41

    One in awk:

    $ awk -v w="Apple" 'BEGIN{RS="( |\n)+"}{c+=($1==w)}END{print c}' file
    4
    

    Explained:

    $ awk -v w="Apple" '     # search word as parameter
    BEGIN {
        RS="( |\n)+"         # set record separator to separate words
        # RS="[[:space:]]+"  # where available
    }{
        c+=($1==w)           # count searched words
    }
    END {                    # in the end
       print c+0             # output count
    }' file
    

    RS="( |\n)+" is tested to work on gawk, mawk and Busybox awk, it failed to work on Debian's original-awk. RS="[[:space:]]+" tested to work on gawk only.

    0 讨论(0)
  • 2021-01-27 18:55

    You can change the grep line to:

    grep -o '\<'"$TOFIND"'\>' "$FILE" | wc -l
    

    or just:

    grep -o "\<$TOFIND\>" "$FILE" | wc -l
    

    Then it will work. It's because the quotes, your double quotes was quoted inside single quotes, so they are not expanded.

    0 讨论(0)
提交回复
热议问题