Skip to content

Instantly share code, notes, and snippets.

@gitcnd
Last active November 9, 2024 22:38
Show Gist options
  • Save gitcnd/2719cd1fc6c053a86a6c672187b26067 to your computer and use it in GitHub Desktop.
Save gitcnd/2719cd1fc6c053a86a6c672187b26067 to your computer and use it in GitHub Desktop.
nowrap - truncates input lines longer than the current terminal width - Usage: cat somefile_with_long_lines.txt | nowrap.pl
#!/usr/bin/perl -w
use strict;
my $cols=`tput cols`; chomp $cols;
while(<>){
chompnl($_); my $l=0; my $out=''; my $ansi='';
while($_ ne '' && $l<$cols) {
if(/(.*?)(\t|\033\[[\d\;]+m)(.*)/) {
my $l1=length($1);
my $add=substr($1,0,$cols-$l%$cols);
$out.=$add; $l+=length($add);
if($2 eq "\t") {
my $ex=8-$l%8;
$out.=$2 if($l+$ex<=$cols);
$l+=$ex;
} else {
$out.=$2; # ANSI codes take up no room
$ansi="\x1b[0m"; # reset the possibly-truncated colours
}
$_=$3;
} else {
my $add=substr($_,0,$cols-$l%$cols);
$out.=$add; $l+=length($add);
$_='';
}
}
print "$out$ansi\n";
}
# chomp() on unix doesn't eat "\r"...
sub chompnl { # Warning: don't stuff up $1
chop $_[0] while((substr($_[0],-1) eq "\015")||(substr($_[0],-1) eq "\012"));
} # chompnl
@gitcnd
Copy link
Author

gitcnd commented Jul 15, 2021

intelligently handles tabs as well as some ANSI escape sequences (color etc)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment