Guidelines

This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

0 votes
171 views
171 views

How can I truncate long output lines at a given number of characters (e.g. 50) on the commandline or in a shell script?

Example:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ultrices vulputate ornare.

should become

Lorem ipsum dolor sit amet, consectetur adipiscing
in Scripting
by (100)
1 13 28
edit history

Please log in or register to answer this question.

1 Answer

0 votes
 

You can use cut with the parameter -c for this purpose:

... | cut -c 1-50

This will truncate each input line longer than 50 characters at 50 characters.

Alternatively you could use sed, but since the syntax is far more complex I'd only recommend that if you want to append an ellipsis to the end of each truncated line (as an indicator that the line was truncated):

... | sed -r 's/^(.{47}).+/\1.../'

Note that for this replacement you need an extended regular expression (-r).

Regex breakdown:

  • ^ anchors the expression at the beginning of a line.
  • (.{47}) matches the next 47 characters (50 minus the length of the ellipsis). . matches any single character except newlines. A positive integer N in curly brackets means "N times the preceding expression." The parentheses put the matched substring in a capturing group, so that it can be used via backreference (\1) in the replacement.
  • .+ matches the rest of the line, so that it gets removed (because it's not referenced in the replacement), but only if it's at least one character long (+ is a modifier that means "one or more times the preceding expression"). That way lines of exactly 50 characters won't have a trailing ellipsis.
by (100)
1 13 28
edit history
...