How to do String slicing to sub strings in Bash shell ?

As the name of post suggests, in this article we will check how to slice a string to sub strings.

To understand this, lets take an example:-

Printing every 2nd character of a string in Bash.

[root@nglinux ~]# string="NGELinux.com"; length=$((${#string} - 1)); 
[root@nglinux ~]# for ((i=0; i<= $length; i=i+2 )); { echo -n "${string:$i:1}"; }; echo
NEiu.o
[root@nglinux ~]# 

The above command looks complex however its pretty simple:

1. string is a variable stores the string "NGELinux.com"
2. length is a variable contains total string length minus 1 i.e. 12 - 1 = 11.
3. for loop from 0 to 11 and increment by 2.
4. "-n" to omit newline character in echo.
5. $(string:0:1) will get the first character i.e. N
6. $(string:2:1) will get the third character i.e. E

And similarly we have the complete output by omitting every other character i.e. NEiu.o.

The above process of breaking a string or its sub strings into parts, is known as string or sub-string slicing in Bash

Leave a Reply

avatar
  Subscribe  
Notify of