Truncate stdin line length?

2019-02-13 13:40发布

I've been parsing through some log files and I've found that some of the lines are too long to display on one line so Terminal.app kindly wraps them onto the next line. However, I've been looking for a way to truncate a line after a certain number of characters so that Terminal doesn't wrap, making it much easier to spot patterns.

I wrote a small Perl script to do this:

#!/usr/bin/perl

die("need max length\n") unless $#ARGV == 0;

while (<STDIN>)
{
    $_ = substr($_, 0, $ARGV[0]);
    chomp($_);
    print "$_\n";
}

But I have a feeling that this functionality is probably built into some other tools (sed?) that I just don't know enough about to use for this task.

So my question sort of a reverse question: how do I truncate a line of stdin WITHOUT writing a program to do it?

9条回答
放我归山
2楼-- · 2019-02-13 14:10

A Korn shell solution (truncating to 70 chars - easy to parameterize though):

typeset -L70 line
while read line
do
  print $line
done
查看更多
来,给爷笑一个
3楼-- · 2019-02-13 14:11

Another tactic I use for viewing log files with very long lines is to pipe the file to "less -S". The -S option for less will print lines without wrapping, and you can view the hidden part of long lines by pressing the right-arrow key.

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-13 14:12

The usual way to do this would be

perl -wlne'print substr($_,0,80)'

Golfed (for 5.10):

perl -nE'say/(.{0,80})/'

(Don't think of it as programming, think of it as using a command line tool with a huge number of options.) (Yes, the python reference is intentional.)

查看更多
淡お忘
5楼-- · 2019-02-13 14:15

Unless I'm missing the point, the UNIX "fold" command was designed to do exactly that:

$ cat file
the quick brown fox jumped over the lazy dog's back

$ fold -w20 file
the quick brown fox
jumped over the lazy
 dog's back

$ fold -w10 file
the quick
brown fox
jumped ove
r the lazy
 dog's bac
k

$ fold -s -w10 file
the quick
brown fox
jumped
over the
lazy
dog's back
查看更多
淡お忘
6楼-- · 2019-02-13 14:17
use strict;
use warnings
use String::FixedLen;

tie my $str, 'String::FixedLen', 4;

while (defined($str = <>)) {
    chomp;
    print "$str\n";
}
查看更多
Emotional °昔
7楼-- · 2019-02-13 14:18

Pipe output to:

cut -b 1-LIMIT

Where LIMIT is the desired line width.

查看更多
登录 后发表回答