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?
-
See also: unix.stackexchange.com/q/175852don_crissti– don_crissti2015-03-25 15:16:06 +00:00Commented Mar 25, 2015 at 15:16
Add a comment
|
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.
-
25The equivalent form
cut -c 1-80may be better for understanding.Libin Wen– Libin Wen2019-10-28 10:57:12 +00:00Commented Oct 28, 2019 at 10:57 -
2fixed command syntax you must supply a range: "some-command | cut -c 1-80"Bernard Hauzeur– Bernard Hauzeur2020-01-27 09:43:07 +00:00Commented Jan 27, 2020 at 9:43
-
5Without the
1it's easy to miss the-before the 80 so I agree it makes more sense.Sridhar Sarnobat– Sridhar Sarnobat2020-02-05 01:05:14 +00:00Commented Feb 5, 2020 at 1:05 -
9I like to use
some-command | cut -c -$COLUMNSwhich uses the entire terminal width, whatever that currently happens to be.Dale C. Anderson– Dale C. Anderson2021-01-18 06:52:54 +00:00Commented 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 touchcreates 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– Abdull2023-08-25 21:44:25 +00:00Commented Aug 25, 2023 at 21:44