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.