Capturing or cutting few characters of a string

by LinuxTitli on May 2, 2006 · 2 comments

Shell scripting is part of my day today life job. Sometime you just need to cut or grab first few characters of a string. For example, consider following string I am using in a script:

IP=”192.168.1.5”
CONF=”something”

I just need to grab network id i.e. 192.168.1 of a string $IP

I can write out

$ test=${IP:0:9}
$ echo $test

It took me more than an hour to find out solution to this tiny problem. BASH man page Parameter Expansion has lots of information. Make sure you read it.

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

We're here to help you make the most of sysadmin work. So, subscribe!

{ 2 comments… read them below or add one }

1 Mayavi July 4, 2006

dude,
you need to use either CUT or some other mechanism.
since your script will need tweaking to handle Network IP like
192.168.128.1
use AWK/GAWK/CUT to split the network address into four parts using “.” as operator.
and then concatenate and use first three.

Reply

2 Raj Mishra September 11, 2007

hi,
it can be written in other ways

$ echo $IP | cut -f1-3 -d”.”

this works fine…

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 13 + 11 ?
Please leave these two fields as-is:
Are you a human being? Solve the simple math so we know that you are a human and not a bot.



Previous post:

Next post: