Results

See more...

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

Contact Us for News Tips, Corrections and Feedback
9 comments
Leave a message...

  •  
    forced lesbian incest4 years, 10 months ago

    hm… cognitively )

  •  
    KattyBlackyard4 years, 10 months ago

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

  •  
    rob mayoff4 years, 10 months ago

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

  •  
    rob mayoff4 years, 10 months ago

    Using only bash builtins:

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

  •  
    Josh4 years, 10 months ago

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

  •  
    mark4 years, 10 months ago

    For some reason I think this all looks ugly …

  •  
    Ken Hirsch4 years, 10 months ago

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

  •  
    Ken Hirsch4 years, 10 months ago


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

    or


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

  •  
    Martin4 years, 10 months ago

    More fun and obscure using a regular expression:

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

    :)

    /M