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.
Contact Us for News Tips, Corrections and Feedback
hm… cognitively )
Hi, very nice post. I have been wonder’n bout this issue,so thanks for posting
My previous comment had its less-than and greater-than eaten.
Using only bash builtins:
while read -r line; do echo “${line: -50}”; done out.txt
@mark:
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.
For some reason I think this all looks ugly …
I meant 49 and 50 in my last comment, but was testing it out with 9 and 10.
awk '{print substr($0, length($0)-9)}' file.txt
or
perl -lne 'print substr($_,-10)' file.txt
More fun and obscure using a regular expression:
cat file.txt | sed -e "s/.*\(.\{50\}$\)/\1/"
:)
/M