2

I want to count the number of words and print the matched pattern lines which matches exactly with following pattern:

abc-ERROR:

The input File contains:

# abc-ERROR: xyxxkkfgfr
# def-Error: aaaaaa
# abc-ERROR.cpp

The output should be:

 1   (count)
 # abc-ERROR: xyxxkkfgfr   (line)
2

You can use grep to get the lines and grep -c to get the number of lines. If you do not like running grep two times, you can use tee and the process substitution (the following is the bash syntax):

grep abc-ERROR: input.txt | tee >( wc -l )
  • No its not working means not giving any output – Bhushan J Apr 17 '13 at 10:02
  • @Bhushan: Works for me. What shell are you running? – choroba Apr 17 '13 at 10:51
  • grep -w make-ERROR "C:\Documents and Settings\bj3\comp_appli.txt" Is it correct syntax..? because its not working at my side.. I m running it through simple shell file (ksh) – Bhushan J Apr 17 '13 at 11:11
  • Sorry I tried wrong one not yours... Thanks a lot – Bhushan J Apr 17 '13 at 11:13
  • I am getting this error : syntax error: got (, expecting Word so, can you please tell me the correct syntax – Bhushan J Apr 17 '13 at 11:15
0

How is this:

$ cat file
# abc-ERROR: xyxxkkfgfr
# abc-ERROR: xyxxkkfgfr
# abc-ERROR: xyxxkkfgfr
# def-Error: aaaaaa
# abc-ERROR.cp
# abc-ERROR: asdgsdgaaf
# abc-ERROR: asdgsdgaaf
# abc-ERROR: tttttttttq

$ awk '/abc-ERROR: /{a[$0]++}END{for(k in a) printf "%d\t(count)\n%s\t(line)\n",a[k],k}' file
1   (count)
# abc-ERROR: tttttttttq (line)
2   (count)
# abc-ERROR: asdgsdgaaf (line)
3   (count)
# abc-ERROR: xyxxkkfgfr (line)
0

There are 2 ways I recommend going about this.

1) Put a function in your bashrc / bash_profile and create an alias to call that function (this will make global usage of this)

2) create a shell script file and can create an alias of that file as well.

#!/bin/bash
function matchString(){
REGEX="$1"
FILE="$2"
RESULTS=$(grep -n "$REGEX" $FILE | awk -F ":" '{print $2 "\tLine: " $1}')
COUNT=$(echo $RESULTS | wc -l)
echo "Count: $COUNT"
echo $RESULTS
}
matchString $1 $2

Calling this file (ie. bash matchString.sh "abc-ERROR:" test.txt) based on your text file will output as this:

Count: 1

abc-ERROR Line: 1

--This function takes 1st arg as the regex pattern (so this can be re-used in any similar scenario) and searches that pattern in the file which is called by the 2nd arg.

1st line of output is the total count of all matched lines, and each line after is the match followed by a tab a line number of that match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.