在文件中查找数字(脚本,bash)

时间:2014-03-11 00:26:59

标签: linux bash command

我想在文件中找到数字或单词。作为第一个参数,它获取您要查找的文件名和第二个数字。

例如我在命令行中写道:

bash script.sh file.txt 6

我得到输出

Number 6 repeats 4 time

这是file.txt

中的内容
5 4 5 6 2 4 6 3 6 6

这是我出现并坚持的代码

para2=$2
while read line
do
    array=($line)
    echo "Value of third element in my array : ${array[3]} "
done < $1

我不知道如何将参数2与每个数组进行比较。我知道在上面的代码中我打印出第三个数组,但我不知道如何遍历每个数组并将它们与参数二进行比较。我的意思是我想通过所有数字并与输入参数进行比较。请求帮助

3 个答案:

答案 0 :(得分:0)

试试这个:

numOccurences=0

while read line
do
    array=($line)

    for i in "${array[@]}"
    do
       if [ "$2" = "$i" ]
       then
           numOccurences=`expr $numOccurences + 1`
       fi
    done
done < $1

echo "$2 occurs $numOccurences times in $1"

程序将读取一行,遍历由该行形成的数组,然后将该值与目标字符进行比较。每次匹配都会更新一个计数器,并在结尾打印结果。

示例输入(file.txt):

5 4 5 6 2 4 6 3 6 6 6 6
6 6
᠎

命令:

/Users/Robert/Desktop/Untitled.sh /Users/Robert/Desktop/file.txt 6

输出:

6 occurs 8 times in /Users/Robert/Desktop/file.txt

答案 1 :(得分:0)

para2=$2
counter=0
while read line
do
    for num in $line
    do
        if [[ $num -eq $para2 ]]
        then let counter = ((counter + 1))
        fi
    done
done < "$1"
echo Number $para2 repeats $counter times

答案 2 :(得分:0)

#!/bin/bash

    echo "Number to be searched $2 "
    echo "File name passed : $1"

filename=$1
count=0

while read line
do
   for word in $line; do
        #echo "Number = $word"
        if [ "$2" == "$word" ]; then
           count=$(expr $count + 1)
        fi
    done
done < $filename

echo $2 is observed $count times