如何grep特定的整数

时间:2011-02-28 13:10:08

标签: grep

我在文件中有一个数字列表,格式为:{integer} \ n。所以可能的列表是:

3
12
53
23
18
32
1
4

我想使用grep来获取特定数字的计数,但是 grep -c“1”文件结果3因为它除了1,12,18之外还考虑了它。我怎么能纠正这个?

虽然到目前为止所有的答案都是合乎逻辑的,我之前想过它们并经过测试,但实际上没有任何效果:

username@domain2:~/code/***/project/random/r2$ cat out.txt
2
16
11
1
13
2
1
16
16
9
username@domain2:~/code/***/project/random/r2$ grep -Pc "^1$" out.txt
0
username@domain2:~/code/***/project/random/r2$ grep -Pc ^1$ out.txt
0
username@domain2:~/code/***/project/random/r2$ grep -c ^1$ out.txt
0
username@domain2:~/code/***/project/random/r2$ grep -c "^1$" out.txt
0
username@domain2:~/code/***/project/random/r2$ grep -xc "^1$" out.txt
0
username@domain2:~/code/***/project/random/r2$ grep -xc "1" out.txt
0

5 个答案:

答案 0 :(得分:4)

使用-x标志:

grep -xc 1 file

这就是它的含义:

-x, --line-regexp
     Select only those matches that exactly match the whole line.

答案 1 :(得分:2)

使用此正则表达式...

\D1\D

...或^1$打开多线模式。

Tested with RegExr他们both work

答案 2 :(得分:2)

除了grep

之外,还有其他一些方法可以做到这一点
$ cat file
3 1 2 100
12 x x x
53
23
18
32
1
4

$ awk '{for(i=1;i<=NF;i++) if ($i=="1") c++}END{print c}' file
2

$ ruby -0777 -ne 'puts $_.scan(/\b1\b/).size' file
2

$ grep -o '\b1\b' file | wc -l
2

$ tr " " "\n" < file | grep -c "\b1\b"
2

答案 3 :(得分:1)

使用例如^123$匹配“行的开头,123,行尾”

答案 4 :(得分:0)

grep -wc '23' filename.txt

它将计算数字23的完全匹配数。