96

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

142

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
  • 23
    The equivalent form cut -c 1-80 may be better for understanding.
    – Libin Wen
    Oct 28, 2019 at 10:57
  • 2
    fixed command syntax you must supply a range: "some-command | cut -c 1-80" 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. Feb 5, 2020 at 1:05
  • 8
    I 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
  • 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
    Aug 25 at 21:44

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