grep

How to grep a specific integer


I have a list of number in a file with format: {integer}\n . So a possible list is:

3
12
53
23
18
32
1
4

i want to use grep to get the count of a specific number, but grep -c "1" file results 3 because it takes into account except the 1, the 12, 18 also. How can i correct this?

Although all the answers until now are logical, and i thought of them and tested before, actually nothing works:

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

Solution

  • There a some other ways you can do this besides 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