Regex: How to print starting or last few characters in Bash shell Linux ?

In this post, we will look at few Regular expressions to get first or last few characters from a string.

This tip is very useful to use in bash shell scripts.

Way 1
This is the method i used to prefer since i remember this always…. 😛
In this method, we will grep a character using “.”
1. Regex to print last four characters of a file.

[root@nglinux ~]# echo "NGELinux" | grep -o "....$"
inux

2. Regex to print first four characters of a file.

[root@nglinux ~]# echo "NGELinux" | grep -o "^...."
NGEL

Way 2
In this method, we will grep a character using “\w”

### To print last four characters
[root@nglinux ~]# echo "NGELinux" | grep -o "\w\w\w\w$"
inux
[root@nglinux ~]# 

### To print first four characters
[root@nglinux ~]# echo "NGELinux" | grep -o "^\w\w\w\w"
NGEL
[root@nglinux ~]#

Way 3
In this method, we will grep a character using “\w” and the occurrences are mentioned using “{}”.

### To print last four characters
[root@nglinux ~]# echo "NGELinux" | grep -Po "\w{4}$"
inux
[root@nglinux ~]# 

### To print first four characters
[root@nglinux ~]# echo "NGELinux" | grep -Po "^\w{4}"
NGEL
[root@nglinux ~]# 

I hope you liked the trick.

Do subscribe to our blog to stay updated with linux/unix articles.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments