Find the answer to your Linux question:
Results 1 to 3 of 3
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, ...
  1. #1
    Just Joined!
    Join Date
    Oct 2009
    Posts
    9

    Extract Data From A Variable

    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?

  2. #2
    Linux Newbie birdman's Avatar
    Join Date
    Mar 2006
    Location
    Ireland
    Posts
    141
    As always, there's probably a better way to do this:

    Code:
    var=20091013
    varY=`echo $var | sed -n "s/\([0-9][0-9][0-9][0-9]\)[0-9][0-9][0-9][0-9]/\1/p"`
    varM=`echo $var | sed -n "s/[0-9][0-9][0-9][0-9]\([0-9][0-9]\)[0-9][0-9]/\1/p"`
    varD=`echo $var | sed -n "s/[0-9][0-9][0-9][0-9][0-9][0-9]\([0-9][0-9]\)/\1/p"`
    Which should output:

    Code:
    $ echo "$varY $varM $varD"
    2009 10 13

  3. #3
    Linux Newbie
    Join Date
    Sep 2004
    Location
    UK
    Posts
    160
    In bash (if that's an good for you try:

    Code:
    var="20091013"
    year="${var:0:4}"
    month="${var:4:2}"
    day="${var:6:2}"
    echo $var $year $month $day should print 20091013 2009 10 13
    In a world without walls and fences, who needs Windows and Gates?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...