Hello Team,
I need bash
script to check if my output is non numerical or empty. if its then my output should display default value as 0
basically, I am reading value from txt file. most of numerical value, in case there is no numerical value or its empty, then my output should be 0
.
example like below:
output=`sed '1!d' $SOURCE_FOLDER/$datafile |awk '{print $6}'`
data="lines1=$output "
output=`sed '1!d' $SOURCE_FOLDER/$datafile |awk '{print $7}'`
data+="lines2=$output "
echo "file value|$date"
Br,Pradeep
RudiC
February 15, 2017, 6:41am
2
In lieu of two sed
invocations followed by an awk
each, you could try a single awk:
awk '{print "lines1=" ($6==$6+0?$6:0) " lines2=" ($7==$7+0?$7:0); exit}' file3
lines1=41531.0 lines2=52529.0
awk '{print "lines1=" ($6==$6+0?$6:0) " lines2=" ($7==$7+0?$7:0); exit}' logfile
lines1=0 lines2=0
1 Like
Another approach using awk:
awk '{printf("lines1=%d lines2=%d\n", $6+0, $7+0); exit }' infile
Originally I was going to use NR==1
to match the first line but RudiC's approach using exit should be much more efficient when the input file has a large number of lines.
Replace %d
format specifiers with %f
, %.2f
, etc if you have non-integer values.
1 Like
RudiC
February 15, 2017, 5:05pm
4
Nice approach! In fact, with the %d
format specifier, you don't need the +0
as both an empty or a string field would result in a 0 to be printed:
cf file[1-3]
file1:
/ home k abc txt ABC DEF
file2:
/ home k abc txt 92 1023
file3:
AB CD EF
awk '{printf("lines1=%d lines2=%d\n", $6, $7); exit }' file1
lines1=0 lines2=0
awk '{printf("lines1=%d lines2=%d\n", $6, $7); exit }' file2
lines1=92 lines2=1023
awk '{printf("lines1=%d lines2=%d\n", $6, $7); exit }' file3
lines1=0 lines2=0
The only drawback is when a field has a string starting with numeric characters like
cat file4
A B C D E F23 24G H
Your approach:
awk '{printf("lines1=%d lines2=%d\n", $6+0, $7+0); exit }' file4
lines1=0 lines2=24
My approach:
awk '{print "lines1=" ($6==$6+0?$6:0) " lines2=" ($7==$7+0?$7:0); exit}' file4
lines1=0 lines2=0
The OP needs to decide which one would satisfy his/her needs.
Thanks all for reply, I have quick question here. how about having multiple lines in single file like below.
.
e.g
100 4 5 101 400
900 1245 789 P
I want to read multiple lines from files and display output related each field.
my output should be like this.
process1= 100
process2 = 900
process3 = 789
process4 = 0
process4 will be 0 since its having non numerical value.
Awk has a built in variable NR which matches the row number of the file so you can test this when extracting your process numbers:
awk '
NR==1 { printf("process1= %d\n", $1+0) }
NR==2 {
printf("process2 = %d\n", $1+0)
printf("process3 = %d\n", $3+0)
printf("process4 = %d\n", $4+0)
exit
}' infile