shell split

Dannyman sez:

# octects
oct1=`echo $subnet | awk -F . ‘{print $1}’`
oct2=`echo $subnet | awk -F . ‘{print $2}’`
oct3=`echo $subnet | awk -F . ‘{print $3}’`
oct4=`echo $subnet | awk -F . ‘{print $4}’`

Later, when reviewing my script, Anonymous Coward offered this little gem:

$ set `echo 10.20.30.40 | tr ‘.’ ‘ ‘`

Ok, that’s a reduction from 12 forks and 8 execs to 3 forks and 2 execs.

but you can do it with zero:

IFS=. set 10.20.30.40

This entry was posted in tech. Bookmark the permalink.

2 Responses to shell split

  1. Danny Howard says:

    Hrmmm.


    $ IFS=. set 10.20.30.40
    $ echo $2

    $ IFS=.
    $ set 10.20.30.40
    $ echo $2

    $ echo $1
    10 20 30 40

    Did I miss something or are you running bash? :)

    -danny

  2. Andrew says:

    It doesn’t work for me either in an interactive bash session. However, it works just fine on Solaris /bin/sh:

    #!/bin/sh
    IFS=.
    set 1.2.3.4
    echo “$1 – $2 – $3 – $4″

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>