1

ここでは、ファイルからパターンを検索するユーザーから入力を受け取り、パターンが見つかったファイルから必要な行数を表示する小さなスクリプトを作成しました。このコードは、標準的な grep の慣習により、パターン行ごとに検索していますが。パターンが同じ行で 2 回発生した場合、出力を 2 回印刷する必要があります。私が何らかの意味を成すことを願っています。

#!/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))

読み取るファイルが 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 に答える