Link to home
Start Free TrialLog in
Avatar of 1 LinePerl
1 LinePerl

asked on

Basic linux/ awk Question

I believe what I have below is way too complicated for such a simple task <not to mention it doesn't work>
awk '{if ($2 !~ /0/) sg="used"; if ($2 ~ /0/) {count["0"]};{if (sg ~/null/) print "used",count}' file.txt

Open in new window

What I am trying to do is :

read file.txt
if
$2 is not "0" on every row, print "used"
else
print the count of rows where the value of $2 is "0"
Avatar of Steven Vona
Steven Vona
Flag of United States of America image

Here is a bash version...

#!/bin/bash
while read line; do
        two=`echo $line | awk '{print $2}'`
        if [ "$two" = "0" ]; then
                echo '$2 is 0'
        else
                echo 'used'
        fi
done

Open in new window


Your can run it like this:

./script.sh < file.txt

You can change it to meet your needs.
I'm not sure if I understand your goal. This is how I'm interpreting your pseudo code:

1) Assuming we have an input file containing 10 rows, and none to nine of them contain "0" in the second column, what should be the final result? According to your question it should be just the word "used".
2) Assuming we have an input file containing 10 rows, and all of them contain "0" in the second column,
what should be the final result? According to your question it should be the number "10" (= the total number of rows in the file).

Is that correct? If so try this:

awk '{if($2!~/0/) sg="used"; else count++} END {if(sg) print sg; else print count}' file.txt
or shorter
awk '{if($2!~/0/) sg="used"} END {if(sg) print sg; else print NR}' file.txt

If my assumptions above are incorrect please explain a bit clearer what you're after.

wmp
ASKER CERTIFIED SOLUTION
Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of 1 LinePerl
1 LinePerl

ASKER

This got me to where was going:

awk '{if($2!~/0/)xcount++}END{if(xcount)print "used",xcount}' file.txt
This pointed me in the right direction:
awk '{if($2!~/0/)xcount++}END{if(xcount)print "used",xcount}' file.txt