Reputation: 917
I have a file containing lines in the following format:
<firstname> <lastname> <day_of_birth> <month_of_birth> <year_of_birth>
I need to display the users who celebrate their birthday at the current date.
I managed to write the script but only by checking if the day == the current day.
How can I write the line with awk where I check if $3 == day, also checking if $4 == month and $5 == year? Thank you
# get current date: day, month, year
day="$(date +'%d')"
month="$(date +'%m')"
year="$(date +'%Y')"
birthdays=$(awk "\$3~/$day/ {print \$1, \$2;}" users.lst)
echo $birthdays
Upvotes: 1
Views: 294
Reputation: 30813
Here is an alternative way:
awk '$3=="'$(date +%d)'"&&$4=="'$(date +%m)'"&&$5=="'$(date +%Y)'"{print $1,$2}' users.lst
Upvotes: 1
Reputation: 203219
You didn't post any sample input so it's a guess, but this is probably what you want:
awk -v date=$(date "+%d/%m/%Y") '$3"/"$4"/"$5 == date {print $1, $2}' file
Upvotes: 4
Reputation: 40718
You can get the current date from within awk
as follows:
awk 'BEGIN {
"date +%d" | getline day
"date +%m" | getline month
"date +%Y" | getline year
}
$3==day && $4==month && $5==year {
print $1,$2
}' users.lst
Upvotes: 3
Reputation: 784968
You cannot just shell variables in awk like this. It might create many problems. You need to pass shell variables to awk using -v awk_var=$shell_var
option.
You can use this awk command:
awk -v d=$day -v m=$month -v y=$year '$3==d && $4==m && $5==y {print $1, $2}' users.lst
However please note the GNU awk has built-in date/time functions and you can just avoid calling date command 3 times before awk like this:
awk '$3==strftime("%d") && $4==strftime("%m") && $5==strftime("%Y")
{print $1, $2}' users.lst
Upvotes: 4