计算文件中出现的次数或更高的值 [英] Counting the number of occurences or higher value in a file
问题描述
我想知道是否有一种方法可以使用AWK或SED查找某些值,这些值高于您在文件内为脚本提供的参数.这是
I was wondering if there was a way to use AWK or SED to find certain values that are higher than the argument you gave to the script inside a file. This being
./script.sh CITY VALUE
在这种情况下,值是2美元或第二个参数,它将作为我们搜索的基础,因此,如果我们有一个文件,
The value, in this case, is the $2 or second argument which is going to the basis of our search, so if we have a file,
dummy2.txt
格式:姓名; ID;专业;电子邮件;评分;访问次数;余额
Format: Name;ID;Profession;email;rating;number of visits;balance
John Trevolta;12334;dentist;gmail;0;0;431
Isabella;4567;dentist;gmail;0;0;400
如果输入,
./script.sh CITY 400
它应该能够从这个确切的dummy2.txt中读取每一列(在本例中为第七列($ 7)),并输出它发现的值大于我们给出的值的次数,因此所需的输出为:
It should be able to read every column ( the seventh in this case ($7)) from this exact dummy2.txt and output the number of times it finds a value higher than the one we gave it so the desired output would be:
1
但是我得到的当前输出如下:
But the current Output I'm given is the following:
1 John Trevolta;12334;dentist;gmail;0;0;431
因此,这是我目前拥有的代码:
So with this, this is my current code that I have for it:
#!/bin/bash
if [ "$#" -eq 0 ]
then
echo "Please insert arguments"
exit 1
elif [ "$#" -lt 2 ] || [ -z "$1" ]
then
echo "Error 404: No arguments found"
exit 1
else
grep -c "$1" dummy.txt
awk -v x=$2 '$7>x{ i++ }END{ print "Found:" i }' dummy2.txt
fi
我已经在评论中添加了一些建议,但不幸的是,它仅打印出来,
I have already added some suggestions found in the comments but unfortunately, it only prints,
Found:
它不会开始计算i,甚至不会说它的价值.我不知道是否需要初始化它,是否需要在其上放置"/"/$以使其可读.
It doesn't start counting the i or even say it's value. I don't know if I need to initialize it or not and if I need to put ''/""/$ on it for it to be read.
推荐答案
由于(缺少)输入,因此假定以下输入(numbers.txt):
Because of (the lack of ) input, assume the following input (numbers.txt):
een 1
twee 2
drie 3
vier 4
vijf 5
zes 6
zeven 7
然后:
awk -v arg1 = 2'$ 2> arg1 {i ++} END {打印找到"我大于"arg1}'numbers.txt
将打印:找到大于2的5行
和:
awk -v arg1 = 5'$ 2> arg1 {i ++} END {打印找到"我大于"arg1}'numbers.txt
将打印:找到大于5的2行
(因为...)
在创建这样的脚本时(将其命名为 test.sh
):
When creating a script like this (lets name it test.sh
):
#!/bin/bash
rm numbers.txt
echo een 1 >>numbers.txt
echo twee 2 >>numbers.txt
echo drie 3 >>numbers.txt
echo vier 4 >>numbers.txt
echo vijf 5 >>numbers.txt
echo zes 6 >>numbers.txt
echo zeven 7 >>numbers.txt
echo acht 8 >>numbers.txt
awk -v arg1=3 '$2>arg1{ i++ }END{ print "Found " i " lines greater than " arg1 }' numbers.txt
awk -v arg1=5 '$2>arg1{ i++ }END{ print "Found " i " lines greater than " arg1 }' numbers.txt
awk -v arg1=$1 '$2>arg1{ i++ }END{ print "Found " i " lines greater than " arg1 }' numbers.txt
输出将是:
$ ./test.sh 7
Found 5 lines greater than 3
Found 3 lines greater than 5
Found 1 lines greater than 7
这篇关于计算文件中出现的次数或更高的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!