在 Linux 中,如何截断命令行输出?

Nik*_*rez 60 linux bash command-line

如果我grep -nr sumthin *在我的源代码目录中,它也会从缩小的 JavaScript 或 CSS 文件中喷出很长的行。我只想获得每行的前 80 个字符。

例如,一个常规grep给我这个:

css/style.css:21:   behavior: url("css/iepngfix.htc")
css/style-min.css:4:.arrow1{cursor:pointer;position:absolute;left:5px;bottom:10px;z-index:13;}.arrow2{cursor:pointer;position:absolute;right:5px;bottom:10px;z-index:13;}.calendarModule{z-index:100;}.calendarFooterContainer{height:25px;text-align:center;width:100%!important;z-index:15;position:relative;font-size:15px!important;padding:-2px 0 3px 0;clear:both!important;border-left:1px solid #CCC;border-right:1px  ... etc.
Run Code Online (Sandbox Code Playgroud)

但我只想得到这个:

css/style.css:21:   behavior: url("css/iepngfix.htc")
css/style-min.css:4:.arrow1{cursor:pointer;position:absolute;left:5px;bottom:
Run Code Online (Sandbox Code Playgroud)

什么 Linux 命令可以做到这一点?

Nik*_*rez 86

天哪,我完全忘记了cut

grep -nr sumthin * | cut -c -80
Run Code Online (Sandbox Code Playgroud)

^ 有诀窍!>_<

  • 如果目的只是为了能够在视觉上很好地看到事物(而不是将输出重定向到某处以供使用),那么“less -S”就是您想要的。`-S` 是 `--chop-long-lines`。基本上,它关闭换行 (6认同)
  • 如果涉及转义序列或颜色代码,那将不起作用;例如`git log --oneline --graph --color=always | cut -c -$COLUMNS` (4认同)

小智 5

除了cut你可以使用fold(在某些情况下fmt)。
foldcoreutils包的一部分。

$ echo "some very long long long text" | fold -w 5   # fold on 5 chars per line
some 
very 
long 
long 
long 
text
Run Code Online (Sandbox Code Playgroud)

fold剪切剩余的文本,而是在下一行输出它。