Given a text file, or the output of a command, how can I truncate it so that every line longer than N
characters (usually N=80
in a terminal) gets shorten to N
characters maximum?
1 Answer
You can use cut
to achieve this (using N=80
here):
some-command | cut -c -80
or
cut -c -80 some-file.txt
Replace 80 with the number of characters you want to keep.
Note that:
- Multi-bytes characters may not be handled correctly, depending on your implementation;
- Multi-characters bytes (aka tabs) may be treated as one char (& this question treats this).
Dale Anderson suggests the use of some-command | cut -c -$COLUMNS
which truncates to the current terminal width.
Libin Wen suggests that the equivalent cut -c 1-80
may be better for understanding.
-
23
-
2fixed command syntax you must supply a range: "some-command | cut -c 1-80" Jan 27, 2020 at 9:43
-
5Without the
1
it's easy to miss the-
before the 80 so I agree it makes more sense. Feb 5, 2020 at 1:05 -
8I like to use
some-command | cut -c -$COLUMNS
which uses the entire terminal width, whatever that currently happens to be. Jan 18, 2021 at 6:52 -
1Using
... cut -c -${SOME_NUMBER} ...
may result in invalid strings, as for example with emojis (which are multibyte characters). Example: Using😎😏😐
(with each of these emoji smiley being a 4-byte character):echo '😎😏😐' | cut -b -7 | xargs touch
creates a file named'😎'$'\360\237\230'
, that is: the first four bytes are correctly interpreted as the Smiling Face with Sunglasses, while the remaining three bytes result in an invalid UTF-8 byte sequence.– AbdullAug 25 at 21:44