98

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

1 Answer 1

146

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.

8
  • 24
    The equivalent form cut -c 1-80 may be better for understanding.
    – Libin Wen
    Commented Oct 28, 2019 at 10:57
  • 2
    fixed command syntax you must supply a range: "some-command | cut -c 1-80" Commented Jan 27, 2020 at 9:43
  • 5
    Without the 1 it's easy to miss the - before the 80 so I agree it makes more sense. Commented Feb 5, 2020 at 1:05
  • 9
    I like to use some-command | cut -c -$COLUMNS which uses the entire terminal width, whatever that currently happens to be. Commented Jan 18, 2021 at 6:52
  • 1
    Using ... 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.
    – Abdull
    Commented Aug 25, 2023 at 21:44

Not the answer you're looking for? Browse other questions tagged .