Ganz Ricanz Ganz Ricanz - 1 month ago 11x
Bash Question

awk command is working in the console but not working inside shell script

I'm filtering the fourth column in a file using below command. it's working fine in the console

[User@ipaddress Now]$ creationTime="8:15 PM"
[User@ipaddress Now]$ awk -F, -v var="$creationTime" '{if($4==var) print}' input.txt
serial1,tech,EU,8:15 PM,gan

Added the same command in shell script but it's not working.

$ cat
creationTime=$(date -d '330 minutes' +"%l:%M %p")

echo $creationTime
awk -F, -v var="$creationTime" '{if($4==var) print}' input.txt

Output while execting the script

[User@ipaddress Now]$ sh
8:15 PM


serial1,tech,APAC,8:09 PM,anz
serial1,tech,EU,8:15 PM,gan


The problem might be that $creation_time contains leading spaces. When you inspect it with echo, they might not be visible, but they will definitely not match $4 in awk. Example:

$ creationTime=$(date -d '330 minutes'  +"%l:%M %p")
$ echo ">${creationTime}<"
> 4:50 PM<

Try instead:

creationTime=$(date -d '330 minutes'  +"%l:%M %p" | sed 's/^ *//')