Remove Character From End of String in Linux

Often you need to remove one or many character at the end of a string, but you don`t know the string lenght. When that happen there is a way to extract the character that you want no matter the lenght.
For that technique to work you need to use rev and cut , rev is a program that reverse the string it received and cut is a tool that extract part of string , either by field or by character.
In this example I will show you how to extract the last 4 charactere of a string.

1

echo $string | rev | cut -c 1-4 | rev
and with a value of "This is a great Rock Band" in the variable string, this will output :

Band

echo $string
Send string to standard output.
rev
Reverse the string.
cut -c 1-4
Extract character one to four.
rev
Reverse the string again to put it back in the orginal order.

About the Author

Stephane Morin

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Sign up for more great content!

>