Updated: Dr. Drang pointed out that the original functions were mostly working but flawed. I’ve updated this whole post.
This is a simple bash function that will take each line of the input piped to it and truncate it at a given length (default 70 characters), optionally inserting an ellipsis or other string if the line is truncated.
Here’s the basic trick, using
sed with an example line length of 60:
Here’s a more complete version of the function. It accepts a
-l switch to truncate from the left instead of the right (default), and a
-s STRING flag to allow the user to specify an ellipsis or other string to add to lines that have been truncated.
These functions can be added to any file that’s sourced during login, such as ~/.bash_profile. Then they can be used like:
cat filename.txt | shorten 20
You can shorten the output of any command:
ls -1 | shorten 15
Example output without
$ ls -1 2016-04* 2016-04-06-recap-march-and-everything-else.md 2016-04-12-arq-5-gets-a-big-speed-boost.md 2016-04-12-the-textexpander-subscription-snafu.md 2016-04-13-web-excursions-for-april-13-2016.md 2016-04-14-pdfpenpro-complete-pdf-power.md 2016-04-15-friday-freebie-infographic-icon-set.md 2016-04-19-udemy-courses-for-30-percent-off.md 2016-04-20-web-excursions-for-april-20-2016.md 2016-04-21-houdahspot-find-everything-fast.md
shorten to 10 characters, with ellipses:
$ ls -1 2016-04* | shorten -s ... 10 2016-04-06... 2016-04-12... 2016-04-12... 2016-04-13... 2016-04-14... 2016-04-15... 2016-04-19... 2016-04-20... 2016-04-21...
Ryan Irelan has produced a series of shell trick videos based on BrettTerpstra.com posts. Readers can get 10% off using the coupon code