Capturing or cutting few characters of a string

Posted on in Categories News last updated May 2, 2006

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.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

2 comment

  1. 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.

Leave a Comment