Skip to content
Advertisement

If a File is Empty, Write Text to First Line

I need to check to see if two files are empty. If they are, then write “-999” to the file, else run an average on the numbers within the file.

Here is the coding I’ve been trying to use:

Code:

if [[ ! -z file1 ]] || [[ ! -z file2 ]]
then 

echo "-999" > file_avg

else

cat file1 >> tmp
cat file2 tmp > file_all
cat file_all | awk 'BEGIN {c = 0; sum = 0;} $1 ~ /^[0-9]*(.[0-9]*)?$/ 
{a[c++] = $1; sum += $1;} END {avg = sum / c; if( (c % 2) == 1 ) {median = a[ int(c/2) ];}
else {median = ( a[c/2] + a[c/2-1] ) / 2;} OFS="t"; print avg;}' file_all
> file_avg

fi

Contents of file_all:

76
76
78
79
75
76
77
78
76

Advertisement

Answer

the appropriate way to check whether a file is empty is using -s not -z (which checks whether the given string is zero).

BTW, your code seems to calculate the median, while you state that you want to calculate the average, which is not the same. I’ve rewritten your script to calculate the average by using bash scripting and not awk.

#!/bin/bash                                                                        

nlines=0                                                                           
total=0                                                                            

if test -s file1; then                                                             
    while read value; do                                                           
        let total=total+value                                                      
        let nlines=nlines+1                                                        
    done < file1                                                                   
fi                                                                                 

if test -s file2; then                                                             
    while read value; do                                                           
        let total=total+value                                                      
        let nlines=nlines+1                                                        
    done < file2                                                                   
fi                                                                                 

if test "${nlines}" -eq "0"; then                                                                                                                                       
    echo "-999" > file_avg                                                      
else                                                                            
    let average=total/nlines                                                    
    echo $average > file_avg                                                    
fi                                                                              
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement