Skip to content
Advertisement

Using Awk to print the unavailable record only once

I am writing an awk script which looks like this inside:

awk -v searchValue="$searchValue" '{ if ($3 == searchValue){
                                                    printf NR".", $1, $2, $3, $4                                          
                                     }
                                     else if ($3!=searchValue) {print "The value that you entered is not available. Please try again."}                                                                      
                                     }' file

This is my file.

One Two 20 100
Three Four 10 500
Five Six 30 800
Seven Eight 20 500

This tries to print the else if method once, but instead, it prints for all of the lines that do not include the searched value. If I entered 20, my output looks like this:

1. One  Two  20 100
The value that you entered is not available. Please try again.
The value that you entered is not available. Please try again.
4. Four Five 20 500

I have to use the awk command to print else if output once. Let’s say if I entered 700. How do I fix it to get this:

The value that you entered is not available. Please try again.

Advertisement

Answer

Perhaps a solution using the END clause? You can set a variable if you find a match, and then use an if in the END to print the message only if no matches are found.

awk -v searchValue="$searchValue" '
  $3 == searchValue { ismatch = 1; print NR".", $0; }
  END { 
    if(!ismatch) print "The value that you entered is not available. Please try again." 
  }' file

Also I’m not sure you really want to be using printf… plain old print seems a better fit here. And $0 is a little easier than listing out $1, $2, $3, $4.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement