Bash – awk: Blank line with date

awkbash

I use the following code to write the online users' process numbers and the date they were checked:

w | tail -n +3 | awk ' 
        { "date +%H:%M:%S" | getline tim}
        {if ($1 != "")
                { if (usr != $1)  {printf("%s\t%d\t%s\n",usr, num, tim);
                                usr = $1; 
                                num = 1 }
                else {num++}   
                }
        }
        END{ 
        if ($1 != "") if (num !=0) printf("%s\t%d\t%s\n",usr, num, tim);}
' > test2
echo

I have a problem. After I run the script, it gives me one line + for the first analyse, where it gives me a blank for usr, 1 for process num and the date, after which it gives me the actual users and stuff.
Can you help me fix it? Or is there a function already for this?

Best Answer

I may be misunderstanding the intent of your script, but wouldn't it be simpler to construct an array containing the counts for each user? something like

w | awk '
BEGIN{"date +%H:%M:%S" | getline tim}; 
NR > 2 {num[$1]++}; 
END {for (usr in num) print usr, num[usr], tim}
'

or

w | awk -v tim="$(date +%H:%M:%S)" '
NR > 2 {num[$1]++}; 
END {for (usr in num) print usr, num[usr], tim}
'
Related Question