E
E
Everal2018-12-29 15:20:56
linux
Everal, 2018-12-29 15:20:56

If how to output 0 if Awk didn't find a value?

How to make awk output 0 if it didn't find a value in a file?
cat /countCodes | awk ' /'$1'/ {print $1} '
Search goes by file

742401 200
   9553 404
   8594 304
   8490 301
    403 499
    311 302
     10 500
      7 408
      4 503
      3 400
3206 access_postdata.log

The script looks for a code like 500 and displays the value 10

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Saboteur, 2018-12-29
@Everal

what value are you looking for? You don't actually "search" - awk simply processes the incoming data, without any check whether it found something there or not.
You set the task more correctly - what exactly are the values, an example of a file. Maybe you don't need awk
grep -oP "\s*\K.*(?=500)" /countCodes || echo "0"

P
pcdesign, 2018-12-29
@pcdesign

echo "hhh" | awk '{ if (/iii/) { print $0 } else { print 0 } }'

S
sergey, 2018-12-30
kuzmin @sergueik

in general
THE AWK LANGUAGE
1. Program structure
An AWK program is a sequence of pattern {action} pairs and user function definitions.
A pattern can be:
BEGIN
END
expression
expression , expression
i.e.
echo 'AB Z' | awk 'BEGIN{ status = 0} /ABC/ {status = 42 } END{ print "status=" status }
will give
status=0
and / a
echo 'AB C' | awk 'BEGIN{ status = 0} /AB C/ {status = 42 } END{ print "status=" status } '
will give
status=42

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question