Reputation: 9
I have an output file, which looks something like this:
value1!value2@value3
value1!value2@value3
value1!value2@value3
I want to find out, with grep
, how many times the value2
appears, so I'm doing this:
n = grep -c 'value2' outputfile.tmp
if[$n!=6] ; then
but when I run it, the console says this:
`"-c: command not found"`
like it doesn't recognize the parameter.
Upvotes: 1
Views: 204
Reputation: 52102
This should already choke on the assignment n =
with a space: Bash parameter assignments can't have spaces. Secondly, to assign the output of a command to a parameter, you have to use command substitution:
n=$(grep -c 'value2' outputfile.tmp)
Notice that this will tell you how many lines contain at least one occurrence of value2
, and not the actual number of value2
. Consider:
$ grep -c 'value2' <<< 'value2value2'
1
If you know that there will only be one value2
per line (or you want to count lines), we're good. If you want to count occurrences, you have to use something like
n=$(grep -o 'value2' outputfile.tmp | wc -l)
grep -o
prints each match on a separate line, and wc -l
counts the lines.
Now, to check if the value of $n
is unequal to six, you use a conditional. Unlike the assignments, this must have spaces.
The !=
comparison is for string comparison; for integers, you should use -ne
("not equal"):
if [ "$n" -ne 6 ]; then
Instead of the test command [ ]
, Bash has the more flexible [[ ]]
conditional epxression:
if [[ "$n" -ne 6 ]]; then
where quoting isn't strictly necessary (but doesn't hurt!).
Or we can use an arithmetic expression:
if (( n != 6 )); then
where any parameter is evaluated without prepending $
.
Upvotes: 2
Reputation: 199
You need to enclose the command with $() to set it to a variable:
n=$(grep -c 'value2' outputfile.tmp)
This is a type of command substitution, see near the bottom of this page: http://www.tldp.org/LDP/abs/html/commandsub.html
Upvotes: 1