How to truncate STDIN line length?

前端 未结 9 1769
醉酒成梦
醉酒成梦 2021-01-05 07:15

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. Ho

相关标签:
9条回答
  • 2021-01-05 07:32

    This isn't exactly what you're asking for, but GNU Screen (included with OS X, if I recall correctly, and common on other *nix systems) lets you turn line wrapping on/off (C-a r and C-a C-r). That way, you can simply resize your terminal instead of piping stuff through a script.

    Screen basically gives you "virtual" terminals within one toplevel terminal application.

    0 讨论(0)
  • 2021-01-05 07:33

    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
    
    0 讨论(0)
  • 2021-01-05 07:37

    Not exactly answering the question, but if you want to stick with Perl and use a one-liner, a possibility is:

    $ perl -pe's/(?<=.{25}).*//' filename
    

    where 25 is the desired line length.

    0 讨论(0)
  • 2021-01-05 07:40

    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.)

    0 讨论(0)
  • 2021-01-05 07:42

    You can use a tied variable that clips its contents to a fixed length:

    #! /usr/bin/perl -w
    
    use strict;
    use warnings
    use String::FixedLen;
    
    tie my $str, 'String::FixedLen', 4;
    
    while (defined($str = <>)) {
        chomp;
        print "$str\n";
    }
    
    0 讨论(0)
  • 2021-01-05 07:44

    Pipe output to:

    cut -b 1-LIMIT
    

    Where LIMIT is the desired line width.

    0 讨论(0)
提交回复
热议问题