Last active
November 9, 2024 22:38
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
intelligently handles tabs as well as some ANSI escape sequences (color etc)