[Linux Tidbits] How to Grab Last ‘X’ No. of Characters of Each Line In Bash Script

In Bash scripting, you might come in a situation where you need to grab the last 'x' no.of characters of each line, regardless of the line length. I found this solution on internet, hope it will help.Follwoing command will get you the last 50 characters from each line:

rev file.txt | cut -c -50 | rev > out.txt

So there you have it, if you’re looking to use cut to “cut” characters from the end of the line, the above will cut 50 characters off of the end. Obviously you can remove the last “> out.txt” to get the output on the screen.

Yes, the cut line does look much cleaner. I usually don’t use cut, because its delimiter matching doesn’t compress multiple chars — this turns out to be inferior to the default awk approach. However, when possible, cut is better.