如何截断STDIN行长度?

时间:2008-09-26 01:49:02

标签: perl cut truncate

我一直在解析一些日志文件,我发现有些行太长而无法显示在一行上,所以Terminal.app将它们包装到下一行。但是,我一直在寻找一种在一定数量的字符后截断一条线的方法,这样Terminal就不会换行,这样就可以更容易地发现模式。

我写了一个小的Perl脚本来执行此操作:

#!/usr/bin/perl

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

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

但是我觉得这个功能可能已经内置到其他一些工具中了(sed?)我还不太了解这个任务。

所以我的问题是一个相反的问题:如何在没有编写程序的情况下截断一行stdin?

9 个答案:

答案 0 :(得分:12)

管道输出到:

cut -b 1-LIMIT

LIMIT是所需的线宽。

答案 1 :(得分:11)

我用于查看具有很长行的日志文件的另一种策略是将文件传递给“less -S”。 less的-S选项将打印行而不包装,您可以通过按右箭头键查看长行的隐藏部分。

答案 2 :(得分:2)

不完全回答这个问题,但如果你想坚持使用Perl并使用单线程,可能是:

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

其中25是所需的行长度。

答案 3 :(得分:0)

通常的方法是

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

高尔夫球(5.10):

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

(不要将其视为编程,将其视为使用具有大量选项的命令行工具。)(是的,python引用是故意的。)

答案 4 :(得分:0)

一个Korn shell解决方案(截断到70个字符 - 虽然很容易参数化):

typeset -L70 line
while read line
do
  print $line
done

答案 5 :(得分:0)

您可以使用将其内容剪辑为固定长度的绑定变量:

#! /usr/bin/perl -w

use strict;
use warnings
use String::FixedLen;

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

while (defined($str = <>)) {
    chomp;
    print "$str\n";
}

答案 6 :(得分:0)

这不是你要求的,但是GNU Screen(包含在OS X中,如果我没记错,在其他* nix系统上常见)可以让你打开/关闭换行(Ca r和Ca Cr)。这样,您可以简单地调整终端的大小,而不是通过脚本来管理内容。

屏幕基本上为您提供了一个顶级终端应用程序中的“虚拟”终端。

答案 7 :(得分:0)

use strict;
use warnings
use String::FixedLen;

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

while (defined($str = <>)) {
    chomp;
    print "$str\n";
}

答案 8 :(得分:0)

除非我忽略了这一点,否则UNIX“fold”命令的目的就是:

$ 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