Using bash interactively I am trying to use cut to prevent the lines from going longer than my terminal width. But when using a command with colorized output all the color gets removed by cut. For example: ls -lG | cut -c 1-$COLUMNS
.
Is there anyway to get cut to preserve the color formatting?
Best Answer
You've got two problems here
ls -G
stops outputting in colour when the output doesn't go to a terminal (here to a pipe instead). GNUls
needs to be passed a--color=always
option, and for BSDls
, you need to set the environmentCLICOLOR_FORCE
to a non-empty value to tell it to always output in color.Colors are achieved by outputting escape sequences that are a sequence of characters like
<ESC>[31m
for foreground red. That doesn't have any width when displayed, but as far ascut
is concerned, that's 5 characters which will count up to$COLUMNS
.So you can't use
cut
here as you need to ignore those escape sequences in the calculation. Instead, you could do something like:There,
sed
does the counting and adds a\e[m
to revert the color to default in case it has been cut in the process.Alternatively, you could tell your terminal not to wrap and do the cutting itself with:
(
tput smam
to restore)You could define a function like:
(the
alias
part to force alias expansion afternowrap
), to be called as: