【问题标题】:Count mutiple occurences of a word on the same line using grep使用 grep 计算同一行中单词的多次出现
【发布时间】:2013-10-31 02:57:56
【问题描述】:

在这里,我制作了一个小脚本,该脚本接受用户从文件中搜索某些模式的输入,并显示该文件中找到该模式的所需行数。尽管由于标准 grep 实践,此代码正在搜索模式行。我的意思是如果模式在同一行出现两次,我希望输出打印两次。希望我能说得通。

#!/bin/sh
cat /dev/null>copy.txt
echo "Please enter the sentence you want to search:"
read "inputVar"
echo "Please enter the name of the file in which you want to search:"
read "inputFileName"
echo "Please enter the number of lines you want to copy:"
read "inputLineNumber"
[[-z "$inputLineNumber"]] || inputLineNumber=20
cat /dev/null > copy.txt
for N in `grep -n $inputVar $inputFileName | cut -d ":" -f1`
do
  LIMIT=`expr $N + $inputLineNumber`
  sed -n $N,${LIMIT}p $inputFileName >> copy.txt
  echo "-----------------------" >> copy.txt
done
cat copy.txt

【问题讨论】:

    标签: shell unix grep


    【解决方案1】:

    据我了解,任务是计算模式出现的次数。可以这样做:

    count=$((`echo "$line" | sed -e "s|$pattern|\n|g" | wc -l` - 1))
    

    假设您有一个文件要读取。然后,代码将如下:

    #!/bin/bash
    
    file=$1
    pattern="an."
    
    #reading file line by line
    cat -n $file | while read input
    do
        #storing line to $tmp
        tmp=`echo $input | grep "$pattern"`
        #counting occurrences count
        count=$((`echo "$tmp" | sed -e "s|$pattern|\n|g" | wc -l` - 1))
        #printing $tmp line $count times
        for i in `seq 1 $count`
        do
            echo $tmp
        done
    done
    

    我检查了这个模式“an”。并输入:

    I pass here an example of many 'an' letters
    an
    ananas
    an-an-as
    

    输出是:

    $ ./test.sh input 
    1 I pass here an example of many 'an' letters
    1 I pass here an example of many 'an' letters
    1 I pass here an example of many 'an' letters
    3 ananas
    4 an-an-as
    4 an-an-as
    

    根据您的需要进行调整。

    【讨论】:

      【解决方案2】:

      使用 awk 怎么样?

      假设您正在搜索的模式在变量 $pattern 中,并且您正在检查的文件是 $file

      count=`awk 'BEGIN{n=0}{n+=split($0,a,"'$pattern'")-1}END {print n}' $file`
      

      或者换行

      count=`echo $line | awk '{n=split($0,a,"'$pattern'")-1;print n}`
      

      【讨论】:

        猜你喜欢
        • 2012-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        相关资源
        最近更新 更多