Paste: Find field offsets in fixed text string

Author: tgunr
Mode: factor
Date: Thu, 7 Mar 2013 19:14:10
Plain Text |
! Given a monospaced string of data e.g. data from a `ps ax' command, 
! return a list of field offsets for data extraction
!
! Example string
! "0123456789012345678901234567890123"
! "  PID   TT  STAT      TIME COMMAND"
! plist: V{ 0 }
! olist: V{ 4 }
! plist: V{ 0 5 }
! olist: V{ 4 9 }
! plist: V{ 0 5 10 }
! olist: V{ 4 9 15 }
! plist: V{ 0 5 10 16 }
! olist: V{ 4 9 15 25 }
! plist: V{ 0 5 10 16 26 }
! olist: V{ 4 9 15 25 33 }
! 
! Result
! H{
!     { "STAT" { 10 15 } }
!     { "COMMAND" { 26 33 } }
!     { "PID" { 0 4 } }
!     { "TIME" { 16 25 } }
!     { "TT" { 5 9 } }
! }

:: field-offsets ( str -- seq )
    ! str first .string+columns
    str first >vector :> rest!
    f :> next!
    f :> wlist!  f :> olist!
    f :> plist!  f :> inword!  0 :> first!
    0 :> pos!    0 :> count!
    [ rest unclip next!  rest!
      next 32 =
      [  inword
        [ 32 wlist ?push wlist!
          pos first + plist ?push plist!  count 1- pos!
          count 1- olist ?push olist!
          1 first!
          ! "plist: " write plist . "olist: " write olist .
        ] when
        f inword! ]
      [ next wlist ?push wlist!  t inword! ]
      if
      count 1+ count!
      rest length 0= not
    ] loop
    wlist >string " " split
    pos first + plist ?push plist!
    count first - olist ?push olist!
    ! "plist: " write plist . "olist: " write olist .
    plist olist [ 2array ] { } 2map-as  
    H{ } zip-as 
    ;

New Annotation

Summary:
Author:
Mode:
Body: