How do I Substring ??

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)??

You could do this

let unix_year_yy=`date "+%g"`

Thanks vino!! :wink:

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!! :slight_smile:

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}

Thank u 2 cfajohnson! :slight_smile:

Very helpfull post!!