dannyman.toldme.com

About Me : Free Style : Good Reads : News and Reaction : Photographs : Technical : Travels : Unsorted

Search:
August 22, 2007
Technical

sh: “split” Shortcut

Recently, I wrote a shell script that had to break an IP address into octets. I wrote:


# 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 '.' ' '`
$ echo $1
10
$ echo $2
20
$ echo $3
30
$ echo $4
40

Which means, you can just set a series of variables to $1, $2, $3, and so forth. In Anon’s example, the IP address is split into words with tr, and the variables set nice and easy with set.

Of course, if your script gets complex, you probably want to avoid relying on those variables. My original code could be re-expressed:


set `echo $subnet | tr '.' ' '`
oct1=$1; oct2=$2; oct3=$3; oct4=$4

Much nicer than invoking awk several times.

Read More

Next: Cable TV vs. Satellite TV
Previous: A True Bay Area Hipster
Categories: Technical
Possibly-Related Posts
HOWTO: Audit User Crontabs
Argument Parsing in Shell Scripts
Shell HOWTO: Remove Duplicate Elements from a Variable
HOWTO: Random Number in Shell Script
Makefile, fortune
Unix Trick: Block-and-Page
HOWTO: Add Print Stylesheet to WordPress

Responses

August 23rd, 2007

((meatspace)) » 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}’` [...]

August 23rd, 2007

dbt

Dude, use IFS. I blohhgged it.

December 11th, 2007

geoff

within awk;

echo 192.168.1.1|awk ‘{gsub(/\./,” “);print “1oct:”$1″ 2oct:”$2″ 3oct:”$3 ” 4oct:”$4}’

maybe convert to an int;

echo 192.168.1.1|awk ‘{gsub(/\./,” “);printf “%d”, 16777216*$1 + 65536*$2 + 256*$3 + $4}’

Comment / Tip

. . . or leave a Tip

Leave a comment . . .

  1. For private messages, e-mail me: dannyman@toldme.com
  2. I will not publish or share your e-mail address.
  3. I will not spam you.
  4. Therefor: no anonymous posts; send me your e-mail address!
(required)
(required)

. . . comments from new posters will be held for screening.

Danny Howard is 100% responsible for the content on this site, except some of it is stolen.

All rights are reserved, unless otherwise noted. Generally, I'm a BSD guy, so you can assume implicit permission to adapt, modify, and redistribute my intellectual property with appropriate attribution. Except some of this content is itself re-appropriated, so you'd best ask first, especially for commercial use. Thanks!

You can contact me via e-mail: dannyman@toldme.com

Most of http://dannyman.toldme.com/ is powered by WordPress.

If you're hip to RSS and whatnot, you can subscribe to this site.

These links are for dannyman: login AND backlinks