Rigger
April 25, 2007, 3:19am
1
Hello everyone.
I'm writing a script in UNIX. The purpose is to get the second character from a variable that stores the system year.
This is the code:
unix_year_yy=`date "+%g"`
This will return "07" in variable unix_year_yy. How can I get the second character (7)??
vino
April 25, 2007, 3:21am
2
You could do this
let unix_year_yy=`date "+%g"`
Next year that may fail. You will effectively be doing:
let yy=08
the leading zero, according to posix, indicates an octal constant and 08 is not a legal octal constant. Also you should be using %y.
$ yy=$(date +%y)
$ echo $yy
07
$ yy=${yy#0}
$ echo $yy
7
$
Rigger
April 25, 2007, 7:14am
5
perderabo:
Next year that may fail. You will effectively be doing:
let yy=08
the leading zero, according to posix, indicates an octal constant and 08 is not a legal octal constant. Also you should be using %y.
$ yy=$(date +%y)
$ echo $yy
07
$ yy=${yy#0}
$ echo $yy
7
$
Thanks Perderabo. I'm not familiar to UNIX, so any help is appreciated.
Thank you both!!
If you really want the second character of a 2-character value:
unix_year_yy=${unix_year_yy#?}
On the other hand, if what you really want is to remove a leading zero, but leave a number greater than 10 as 2 digits, read on.
If you have GNU date (standard on Linux systems):
unix_year_yy=`date "+%-g"`
Otherwise, remove the leading zero (if there is one) with parameter expansion:
unix_year_yy=`date "+%g"`
unix_year_yy=${unix_year_yy#0}