这里我创建了一个小脚本,它从用户搜索文件中的某些模式中获取输入,并显示找到该模式的文件所需的行数。虽然这段代码是由于标准的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 :(得分: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
根据您的需要进行调整。
答案 1 :(得分: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}`