[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.

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

9 comments

  • forced lesbian incest

    hm… cognitively )

  • KattyBlackyard

    Hi, very nice post. I have been wonder’n bout this issue,so thanks for posting

  • rob mayoff

    My previous comment had its less-than and greater-than eaten.

  • rob mayoff

    Using only bash builtins:

    while read -r line; do echo “${line: -50}”; done out.txt

  • Josh

    @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.

  • mark

    For some reason I think this all looks ugly …

  • Ken Hirsch

    I meant 49 and 50 in my last comment, but was testing it out with 9 and 10.

  • Ken Hirsch


    awk '{print substr($0, length($0)-9)}' file.txt

    or


    perl -lne 'print substr($_,-10)' file.txt

  • Martin

    More fun and obscure using a regular expression:

    cat file.txt | sed -e "s/.*\(.\{50\}$\)/\1/"

    :)

    /M