如何在Bash的tail命令中添加缩进?

3

在查看长行时,会发生自动换行。但是,在查看日志文件时,需要清晰地看到每一行的开头和结尾。因此,在使用 tail 命令查看日志时,如何添加缩进呢?可以将自动换行从第 10 列开始,而不是从第 0 列开始。例如:

this is a very long line to simulate how a line would wrap in a terminal window
suppose this is the wrapping and it is just the same line the continues here.
this is another very long line to simulate how a line would wrap in a terminal window
suppose this is the wrapping and it is just the same line the continues here.

对比

this is a very long line to simulate how a line would wrap in a terminal window
    suppose this is the wrapping and it is just the same line the continues here.
this is another very long line to simulate how a line would wrap in a terminal window
    suppose this is the wrapping and it is just the same line the continues here.

请注意,我并不是尝试修改行保存到日志文件的方式,而只是使用不同的格式显示该行。

cat 命令有 -n-E 选项,可以在某些情况下提高可读性。虽然不完全符合要求,但仍然很有用。 - keltar
2个回答

8
只需将尾部管道传递到您选择的格式化程序中。一个简单的perl脚本应该可以解决:
tail log-file | perl -pe 's/(.{80})/$1\n\t/g'

会使用制表符缩进行。如果你正在执行tail -f,你可能希望通过以下方式最小化缓冲:

tail -f log-file | perl -pe '$|=1; s/(.{80})/$1\n\t/g'

2

如果:

  • 您正在使用GNU fmt (Linux)
  • 固定的缩进为3个空格也可接受
  • 您的日志行每N个字符至少有1个制表符或空格,其中N是选择的最大行宽度

例如,请尝试:

tail -f log | fmt -t
  • 默认情况下,每行最多可以显示75个字符。如果您需要指定自定义宽度,请使用-w参数;例如:-w 80
  • fmt不会在单词中间断开,这有助于提高可读性。但是,如果没有空格或制表符,它将不会分割。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接