CLI one-liners explained

If you want to cut a specific number of characters from the end of a string in bash, you could use following construction :

rev | cut -b 4- | rev

For example, piping it with a command that gives a string as an output :

uname -r | rev | cut -b 4- | rev

The above command removes three characters from end of the string.

All it is doing is just using standard linux commands to get the job done. Explaining it, here is how it goes step by step from the start :

0.
uname -r – Just an example of command that returns a string. It might have been echo “12345678” for above usage.

1.
rev – command reverts a string character by character.

2.
cut -b 4- – command cuts the string in given position. With used options it will display the input string from 4th byte to the end, therefore cutting first three bytes(characters).

3.
rev – string reversing again.

As we had specific number of characters to remove (3 in this example), but the characters were unknown to us, we could not use searching and replacing tools like sed. As cut command does not support cutting backwards from the end of string, we had to think differently. We reverted the string, so last three characters became the first three characters, then used cut with pretty standard options to display only characters from 4th one to the end, then reverted the string again to get the original order of characters.

This entry was posted in Managed Hosting. Bookmark the permalink.

Leave a Reply

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=""> <strike> <strong>