Shell Tricks: shorten every line of output

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:

short () {
	cat | sed -E "s/(.{60}).*$/\1/"
}

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.

# Truncate each line of the input to X characters
# flag -s STRING (optional): add STRING when truncated
# switch -l (optional): truncate from left instead of right
# param 1: (optional, default 70) length to truncate to
shorten () {
	local helpstring="Truncate each line of the input to X characters\n\t-l              Shorten from left side\n\t-s STRING         replace truncated characters with STRING\n\n\t$ ls | shorten -s ... 15"
	local ellip="" left=false
	OPTIND=1
	while getopts "hls:" opt; do
		case $opt in
			l) left=true ;;
			s) ellip=$OPTARG ;;
			h) echo -e $helpstring; return;;
			*) return 1;;
		esac
	done
	shift $((OPTIND-1))

	if $left; then
		cat | sed -E "s/.*(.{${1-70}})$/${ellip}\1/"
	else
		cat | sed -E "s/(.{${1-70}}).*$/\1${ellip}/"
	fi
}

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 shorten:

$ 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

And with 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 TERPSTRA.

Brett Terpstra

Brett is a writer and developer living in Minnesota, USA. You can follow him as ttscoff on Twitter, GitHub, and Mastodon. Keep up with this blog by subscribing in your favorite news reader.

This content is supported by readers like you.