i tried to use awk to find some fields in a file using a bash script, if the field exists it executes the required commands, but if it does not exists it does not execute the required commands. Am not quite sure what am doing wrong.
this is the script problems.sh
#!/bin/bash
#what happens awk finds nothing
check(){
(awk '$0 =="milk" {print $1}' trial.txt \
| uniq -c \
| awk '{ if ($1 > 1) \
print $1 ,"record found"; \
else if($1 == 1)
print $1, "record of " $2 ,"found";
else if($1 == "")\
print "no record of " $2 ,"found";\
else if(length($1) == 0)
print "no record of " $2 , "found";\
else
print "nothing happened here"
}')
}
echo "what happens when awk finds nothing"
check
this is the trial.txt file
choco
milk
ginger
bread
milk
apple
output>>what happens when awk finds nothing
2 record found
i tried this and there was no output
#!/bin/bash
#what happens awk finds nothing
check(){
(awk '$0 =="fire" {print $1}' trial.txt \
| uniq -c \
| awk '{ if ($1 > 1) \
print $1 ,"record found"; \
else if($1 == 1)
print $1, "record of " $2 ,"found";
else if($1 == "")\
print "no record of " $2 ,"found";\
else if(length($1) == 0)
print "no record of " $2 , "found";\
else
print "nothing happened here"
}')
}
echo "what happens when awk finds nothing"
check
output>>
CodePudding user response:
What happens when searching for fire
:
- 1st
awk
script finds nothing so generates NO output - follow-on
uniq
has no input so it also generates NO output - 2nd
awk
script is thus fed the equivalent of an empty file - 2nd
awk
script only prints a message when it has an input line to process
One approach to handling an empty file (ie, no input lines) is to add some logic in an END {}
block; adding an END{}
block to OP's 2nd awk
:
awk '
{ if ($1 > 1) print $1 ,"record found"
else if ($1 == 1) print $1, "record of " $2 ,"found"
else if ($1 == "") print "no record of " $2 ,"found"
else if (length($1) == 0) print "no record of " $2 , "found"
}
END { if (NR==0) print "nothing happened here" }
'
Generally speaking once you decide to use awk
there's usually no need for the uniq
, nor the need for multiple awk
calls.
Consider one possible rewrite of the check()
function:
check() {
awk -v x="${1}" '
$0 == x { c }
END { if (c > 1) print c, "records of", x, "found"
else if (c == 1) print c, "record of", x, "found"
else print "no record of", x, "found"
}
' trial.txt
}
Take for a test drive:
$ check milk
2 records of milk found
$ check choco
1 record of choco found
$ check fire
no record of fire found