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
	while getopts "hls:" opt; do
		case $opt in
			l) left=true ;;
			s) ellip=$OPTARG ;;
			h) echo -e $helpstring; return;;
			*) return 1;;
	shift $((OPTIND-1))

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

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*

And with shorten to 10 characters, with ellipses:

$ ls -1 2016-04* | shorten -s ... 10

Ryan Irelan has produced a series of shell trick videos based on posts. Readers can get 10% off using the coupon code TERPSTRA.