Last active
July 15, 2021 01:00
-
-
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 | |
# truncates input lines longer than the current terminal width | |
# Usage:- | |
# cat somefile_with_long_lines.txt | nowrap.pl | |
use strict; | |
my $cols=`tput cols`; chomp $cols; | |
while(<>){ | |
chompnl($_); my $tmp=$_; my $add=0; | |
while($tmp=~/(.*?)(\033\[[\d\;]+m)(.*)/) { | |
$add+=length($2) if(length($1)<$cols); # How much of the string we're about to cut containts non-printing chars | |
$tmp=$1 . $3; | |
} | |
while($tmp=~/(.*?)\t(.*)/) { | |
my $spc=8-(length($1) % 8); | |
$tmp=$1 . ( ' ' x $spc ) . $2; | |
$add-=($spc-1); # And how much is tabs too | |
} | |
my $p=substr($_,0,$cols+$add); | |
if($p=~/(\033(?:\[|)[\d\;]{0,})$/) { # cut an escape in half... oops | |
$p=substr($p,0,length($p)-length($1)); | |
} | |
print "$p\n"; | |
} | |
# chomp() on unix doesn't eat "\r"... | |
sub chompnl { | |
chop $_[0] while((substr($_[0],-1) eq "\015")||(substr($_[0],-1) eq "\012")); | |
} # chompnl | |
sub reallen { # Return how big a string was without the ANSI in it | |
my($tmp)=@_; | |
&chompnl($tmp); | |
my $add=0; | |
while($tmp=~/(.*?)(\033\[[\d\;]+m)(.*)/) { | |
$add+=length($2); | |
$tmp=$1 . $3; | |
} | |
return length($tmp); | |
} |
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)