Capturing or cutting few characters of a string

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.


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 2 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
2 comments… add one
  • Mayavi Jul 4, 2006 @ 19:18

    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.

  • Raj Mishra Sep 11, 2007 @ 3:46

    hi,
    it can be written in other ways

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

    this works fine…

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum