Steffi
Steffi

Reputation: 917

More than one condition in awk

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

Answers (4)

jlliagre
jlliagre

Reputation: 30813

Here is an alternative way:

awk '$3=="'$(date +%d)'"&&$4=="'$(date +%m)'"&&$5=="'$(date +%Y)'"{print $1,$2}' users.lst

Upvotes: 1

Ed Morton
Ed Morton

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

H&#229;kon H&#230;gland
H&#229;kon H&#230;gland

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

anubhava
anubhava

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

Related Questions