2013-10-31 62 views
0

在這裏,我製作了一個小腳本,用於從用戶搜索文件中的某些模式並顯示找到該模式的文件中所需的行數。儘管由於標準的grep練習,此代碼正在尋找模式線。我的意思是如果模式在同一行出現兩次,我希望輸出打印兩次。希望我有所幫助。使用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 

回答

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 

我檢查了模式「一個」。輸入:

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 

適應這個您的需求。

0

如何使用awk?

假設您正在搜索的模式是變量$模式,正在檢查的文件$文件 的

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}` 
相關問題