1

I am trying to see in how many lines a specific string exist. While using grep -c ^$string $file_name I dont have a problem, but I need to use the 'awk' command in my project. I tried using awk '/$string/ {print}' $file_name, but returns 0 instead of 1. Please help me!

Thomas Hansen
  • 775
  • 1
  • 6
  • 17
  • 1
    See [how-do-i-find-the-text-that-matches-a-pattern](https://stackoverflow.com/questions/65621325/how-do-i-find-the-text-that-matches-a-pattern) then clarify your question by changing the word "pattern" to "string" or "regexp", whichever one you mean, and adding concise, testable sample input and expected output. – Ed Morton Jan 16 '21 at 18:42

3 Answers3

3

You need to fix 2 things in your attempt, 1st- How to pass a shell variable into awk program by using -v option(where string is your shell variable). 2nd- Use of -c option of grep to get count of string per line. To apply 2nd option use gsub function of awk to globally substitute all occurrence of str(string shell variable in awk) with its own value and keep adding the substitution value to variable count, in the END block of this awk program print the value of count variable which will have total number of occurrences of string per line in it for whole Input_file.

awk -v str="$string" '{count+=gsub(str,"&")} END{print count}' Input_file

NOTE: Above solution will count each and every occurrence of string's value per line, in case you need to count just always very first value of string in each line then change from gsub to sub in above program.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

As pointed out already, you could pass your variable to awk using the -v option. If you want "to see in how many lines a specific string exist" as grep -c, another option is to use match.

You could increment count by 1 for each match and return the count at the end, or 0 if there are no matches.

awk '
match($0, /yourpattern/) {
  count++
}
END{print count ? count : 0}' file
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

You could also try:

awk -v s="$string" 'BEGIN { i=0 } { index($0, s) && ++i } END { print i }' file
phranz
  • 71
  • 5