1

在这里,我制作了一个小脚本,该脚本接受用户从文件中搜索某些模式的输入,并在找到该模式的文件中显示所需的行数。尽管由于标准 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
4

2 回答 2

0

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

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

根据您的需要进行调整。

于 2013-10-31T19:14:31.833 回答
0

用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}`
于 2015-04-17T19:34:42.490 回答