Brief Explanation: String and Array Slicing in Bash Shell Linux.

Today in this post, we will look how to do string or array slicing in bash shell linux by breaking the complete array/string into parts.

We have seen one example in our previous post here.

Here we will expand earlier article to understand the string slicing concepts in detail.

String Slicing (into Substrings)

Taking variable

a=NGELinux

1. Slice Beginning Characters

### Slice first character from string a
[root@nglinux ~]# echo ${a:1}
GELinux

### Slice 2 starting characters
[root@nglinux ~]# echo ${a:2}
ELinux

### Slice starting 4 characters
[root@nglinux ~]# echo ${a:4}
inux

2. Slice End Characters, or, Get Initial sub strings

### Get a substring from starting to 3 characters
[root@nglinux ~]# echo ${a::3}
NGE

### From starting to 4 characters
[root@nglinux ~]# echo ${a::4}
NGEL
[root@nglinux ~]# 

3. Get Last Sub Strings

### Get last three characters
[root@nglinux ~]# echo ${a: -3}
nux

### Get last 1 character
[root@nglinux ~]# echo ${a: -1}
x

4. Slice a Sub-String from start & end index

### Gets 5 characters after 3rd Character
[root@nglinux ~]# echo ${a:3:5}
Linux

### Gets 1 character after 3rd Character
[root@nglinux ~]# echo ${a:3:1}
L
[root@nglinux ~]# 

Bash Array Slicing (into sub-arrays)

Considering below array:

array=('Monday' 'Tuesday' 'Wensday' 'Thursday' 'Friday' 'Saturday' 'Sunday')

1. Slice beginning Array elements

### Omit 1st element from array
[root@nglinux ~]# echo ${array[@]:1}
Tuesday Wensday Thursday Friday Saturday Sunday

### Omit first three elements from array
[root@nglinux ~]# echo ${array[@]:3}
Thursday Friday Saturday Sunday
[root@nglinux ~]# 

2. Get Last Array Elements

### Get last element of Array.
[root@nglinux ~]# echo ${array[@]: -1}
Sunday

### Get last three elements of Array.
[root@nglinux ~]# echo ${array[@]: -3}
Friday Saturday Sunday
[root@nglinux ~]# 

3. Getting Sub-Arrays

### Get 2 elements starting from 2nd index of Array.
[root@nglinux ~]# echo ${array[@]:2:2}
Wensday Thursday

### Get 1 element starting from 2nd index of Array.
[root@nglinux ~]# echo ${array[@]:2:1}
Wensday
[root@nglinux ~]# 

Seems interesting, now you can slice any of the string or array in bash comfortably.

Do post your questions or suggestions below.

4 1 vote
Article Rating
Subscribe
Notify of
guest

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Daniel
Daniel
3 years ago

Consider adding how to trim the last n characters: ${a::-n}
That’s what I was looking for and had to figure it out.

subham
subham
4 years ago

Nice explanation