fonction de tokenisation en bash

Inutile (le fork d'un awk est plus rapide :), mais peut servir d'exemple pour les manipulations de chaines de caracteres.

fonction

  function tokenize {
    [ "$2" = "" ] && return 0
    a_tok=()
    fnum=0
    a_faddr=(0)
    string="$1"
    len="${#string}"
 
    for (( k=$len+1 ; k--;))
    do
      if [ "${string:$len-$k:1}" = "$2" ]
      then
        let pos=$len-$k+1
        let fnum++
        a_faddr[$fnum]=$pos
      fi
    done
 
    a_tok[0]=${string:0:${a_faddr[1]}-1}
 
    for (( k=$fnum+1 ; k--;))
    do
      if [ $k -ne 1 ]
      then
        let len=${a_faddr[$fnum-$k+2]}-${a_faddr[$fnum-$k+1]}-1
        a_tok[$fnum-$k+1]=${string:${a_faddr[$fnum-$k+1]}:$len}
      else
        a_tok[$fnum]=${string:${a_faddr[$fnum-$k+1]}}
      fi
    done
 
    let fnum++
    return $fnum
  }

exemple d'utilisation

  tokenize "test0 test1 test2 test3" " "
  tok_nb=$?
 
  for ((k=$tok_nb; k--;))
  do
    echo ${a_tok[$tok_nb-$k-1]}
  done
shell/tokenisation_en_bash.txt · Last modified: 2010/01/12 13:29 (external edit)
www.chimeric.de Creative Commons License Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0