Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split date variable into components

Tags:

string

bash

split

I have a string from a log that's the equivelent of this....

a="20131202"

I need to seperate it out in to the 3 components.

I am assuming sed is the tool

Can I get a little guidance?

like image 766
user1930517 Avatar asked Feb 13 '26 22:02

user1930517


2 Answers

Parameter expansion is a better tool:

a=20131202
year=${a:0:4}
month=${a:4:2}
day=${a:6:2}
like image 131
choroba Avatar answered Feb 16 '26 19:02

choroba


An alternative using regular expressions:

[[ $a =~ (....)(..)(..) ]]
year=${BASH_REMATCH[1]}
month=${BASH_REMATCH[2]}
day=${BASH_REMATCH[3]}
like image 24
chepner Avatar answered Feb 16 '26 21:02

chepner