Reputation: 3
I have this script which works fine
#!/bin/bash
if [ $# -lt 1 ]
then
echo "USAGE: `basename $0` username"
exit 1
fi
logins=`last | grep $1`
times=`echo "$logins" | awk '{print $10}'`
timesCleared=`echo "$times" | sed -e 's/(//' -e 's/)//'`
minutes=`echo "$timesCleared" | awk -F: '{ print $1*60+$2}'`
total=0
for m in $minutes
do
total=$(( $total + $m ))
done
echo $total > out.txt
cat out.txt
but, for an example, when i try this command in the interactive shell it doesn't work ( echo $minutes gives a different output):
echo "in 02:16 00:28 00:16 00:25 02:44 00:09" | awk -F: '{ print $1*60+$2;}'
it prints 16
if i write echo $minutes in the scripts it gives me the right output:
0 136 28 16 25 164 9
Does anyone know why is this?
Upvotes: 0
Views: 521
Reputation: 241671
The variables in your script contain newlines, which are important. What is being sent to awk
in the line which assigns to the variable minutes
is not
in 02:16 00:28 00:16 00:25 02:44 00:09
as in your command-line, but rather
in
02:16
00:28
00:16
00:25
02:44
00:09
In the first case, awk sees $1
as in 02
and $2
as 16 00
. In the second case, it works on each line individually. When awk converts a string to a number, it uses only the first characters of the string; if it does not find a number at the beginning (as with the string in 02
), it converts it to 0 without any error message.
You can use the RS
awk pseudo-variable to set the record separator to a space:
echo "in 02:16 00:28 00:16 00:25 02:44 00:09" |
awk -F: -v RS=' ' '{ print $1*60+$2;}'
Alternatively, you could echo the string with newlines:
echo "in
02:16
00:28
00:16
00:25
02:44
00:09" | awk -F: '{ print $1*60+$2;}'
Upvotes: 2
Reputation: 189317
The string you echo
in the script is newline-separated, not space-separated; so the command you tried interactively is not doing the same thing.
To reproduce what's going on in the script, try
echo "in 02:16 00:28 00:16 00:25 02:44 00:09" |
tr ' ' '\n' |
awk -F: '{ print $1*60+$2;}'
Upvotes: 2