-1

I need a help regarding awk print f in shell script.

Please see the below my script

#!/bin/sh
date_time=`date '+%d-%b-%Y_%H:%M:%S'`
usr="test"

echo "Hai" | awk -V '{
printf("==========================================\n");
printf("|%10s|%10s|\n","Date" $date_time);
printf("|%10s|%10s|\n","user" $usr);
printf("==========================================\n");
}'

I want output as below

==============================
| date | 14-Jan-2016_16:49:40|
| user | Test                |
==============================
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Chandan Hp
  • 45
  • 1
  • 7

1 Answers1

1

You might be looking for this :

#!/bin/sh
date_time=`date '+%d-%b-%Y_%H:%M:%S'`
usr="test"
printf "==================================\n"
printf "|%10s |%20s| \n" "Date" "$date_time"
printf "|%10s |%-20s| \n" "User" "$usr"  # here - before 20 is for left align
printf "==================================\n"

If for some reason awk is mandatory try the below stuff :

#!/bin/sh
date_time=`date '+%d-%b-%Y_%H:%M:%S'`
usr="test"
awk -v date_time="$date_time" -v usr="$usr" 'BEGIN{
printf "==================================\n"
printf "|%10s |%20s|\n","Date",date_time
printf "|%10s |%-20s|\n","User",usr
printf "==================================\n"
}' </dev/null
sjsam
  • 21,411
  • 5
  • 55
  • 102
  • You should probably quote all the variables, otherwise `printf` will generate multiple lines of output, and/or the shell will do funny stuff with the value when interpolating it. See further http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable – tripleee Jan 14 '16 at 12:34