Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extract Data From A Variable

Status
Not open for further replies.

Grizzly521

Technical User
Oct 12, 2009
7
US
Hi Im wondering how to extract data from a variable, maybe using SED or AWK. I have a variable that contains YYYYMMDD, something like var=20091013. Can I extract the year, YYYY, to varY, the month, MM, to varM and the day, DD to varD?
 
Hi

Depends on your shell. Probably the simplest and fastest :
Code:
[navy]varY[/navy][teal]=[/teal][green][i]"${var:0:4}"[/i][/green]
[navy]varM[/navy][teal]=[/teal][green][i]"${var:4:2}"[/i][/green]
[navy]varD[/navy][teal]=[/teal][green][i]"${var:6:2}"[/i][/green]
Tested with [tt]bash[/tt] and [tt]mksh[/tt].

Feherke.
 
man expr

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Here's another way (which may not work on Linux, depending on your shell):

Code:
echo $var | sed 's/\(....\)\(..\)\(..\)/\1 \2 \3/' | read varY varM varD



Annihilannic.
 
I like Anni's solution best, but here's another way in Korn shell...
Code:
VAR=20091014

YYYY=${VAR%????}
DD=${VAR#??????}
MM=${VAR%??} ; MM=${MM#????}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top