【问题标题】:To find number of occurrences of a word taken as input from command line in unix在 unix 中查找从命令行输入的单词的出现次数
【发布时间】:2019-03-03 09:52:09
【问题描述】:

对于包含file1.txt的文件

Apple fruit Apple tree
Tree AApple AApklle Apple apple
TREE
Apple

我想查找单词Apple 的出现次数。输出应为4
我的 script.sh 文件包含

#!/bin/bash
FILE="$1"
TOFIND="$2"
if [ -f "$FILE" ];
then
grep -o '\<"$TOFIND"\>' "$FILE" | wc -l
fi

当我尝试使用时

bash script.sh file1.txt Apple

输出显示0。请帮忙解决这个问题。

【问题讨论】:

标签: unix command-line grep


【解决方案1】:

使用 GNU awk 进行多字符 RS:

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

或使用 shell 变量:

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

【讨论】:

    【解决方案2】:

    awk 中的一个:

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

    解释:

    $ 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)+" 经测试可在 gawk、mawk 和 Busybox awk 上运行,但无法在 Debian 的 original-awk 上运行。 RS="[[:space:]]+" 经测试仅适用于 gawk。

    【讨论】:

    • 你应该提到这些对于多字符 RS 来说是 gawk-only,你应该打印 c+0 以确保为空文件而不是空字符串输出一个数字。
    【解决方案3】:

    您可以将 grep 行更改为:

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

    或者只是:

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

    然后它将起作用。这是因为引号,你的双引号被引用在单引号内,所以它们没有被扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      相关资源
      最近更新 更多