0

I'm searching through my bash history log for all the typed (started) commands which included the string x. For some reason, the homework checker always says that the number I'm giving is bigger than the actual one.

Here is what I've typed :

grep -o 'x' "/home/user/.bash_history" | wc -l >> FILE
2
  • Why are you using -o in grep?
    – njsg
    Nov 26, 2015 at 15:35
  • 1
    grep's -c option might come in useful. Nov 26, 2015 at 15:36

2 Answers 2

3

I don't know what homework checker you are referring to but the issue here is probably that you are not counting lines with x, youi are counting occurences of x. The -o flag makes grep print only the matched portion of a line, if there are many xs on the same line, it will print each of them separately:

$ echo "xxx" | grep -o x
x
x
x

So, you don't want -o there. You also don't need wc, that's what grep's -c option is for:

$ history | grep -c x
1001

In the future, make sure to read a command's man page before using its options. That will save you a lot of trouble.

2

You need a better search, the grep command can search using regular expressions.

From man grep:

DESCRIPTION
grep  searches  the  named  input  FILEs for lines containing a 
match to the given PATTERN.

And as "Ulrich Schwarz" said, you can use the -c parameter to count.

From man grep:

-c, --count
Suppress normal output; instead print a count of matching lines for
each input file.

So, searching through the bash_history for a command execution using regular expressions and then counting them:

grep -E "EXP" .bash_history

or just

grep "EXP" .bash_history

Example: If you want to count the amount of 'rm' commands:

grep -E ^rm* /home/<user>/.bash_history -c

or just

grep ^rm* /home/<user>/.bash_history -c

Example 2: If you want to count the amount of commands that has the string X:

grep -E X /home/<user>/.bash_history -c

or just

grep X /home/<user>/.bash_history -c

For more info about regular expressions: GNU - grep-regular-expression-syntax

1
  • 1
    Note that even without -E, grep matches regular expressions; just not the exact same type of regular expressions.
    – dhag
    Nov 26, 2015 at 16:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .