当一次拖尾多个文件时,如下所示,有没有办法在每行的开头显示文件名?
tail -f one.log two.log
Run Code Online (Sandbox Code Playgroud)
电流输出
==> one.log <==
contents of one.log here...
contents of one.log here...
==> two.log <==
contents of one.log here...
contents of two.log here..
Run Code Online (Sandbox Code Playgroud)
寻找类似的东西
one.log: contents of one.log here...
one.log: contents of one.log here...
two.log: contents of two.log here...
two.log: contents of two.log here...
Run Code Online (Sandbox Code Playgroud)
tail -f ...your-files |
awk '/^==> / {a=substr($0, 5, length-8); next}
{print a":"$0}'
Run Code Online (Sandbox Code Playgroud)
\谢谢{don_cristti}
GNU Parallel有一组不错的选项,可以很容易地做这样的事情:
parallel --tagstring "{}:" --line-buffer tail -f {} ::: one.log two.log
Run Code Online (Sandbox Code Playgroud)
输出将是:
one.log:这里 one.log 的内容... one.log:这里 one.log 的内容... two.log: 这里的 two.log 的内容... two.log: 这里的 two.log 的内容...
--tagstring=str用字符串str标记每个输出行。从parallel 手册页:--tagstring 字符串
用字符串标记行。每个输出行都将加上
str 和 TAB (\t)。str 可以包含替换字符串,例如 {}。
使用-u、--onall 和--nonall 时会忽略--tagstring。
所有出现的{}将被并行的参数替换,在这种情况下,是日志文件名;即one.log和two.log(之后的所有参数:::)。
该选项--line-buffer是必需的,因为如果该命令完成,将打印命令(例如tail -f one.log或tail -f two.log)的输出。由于tail -f将等待文件增长,因此需要按行打印输出--line-buffer。再次来自parallel 手册页:
--line-buffer(alpha 测试)
基于行的缓冲输出。--group 将保留输出
一起完成整个工作。--ungroup 允许输出与
半条线来自一份工作,半条线来自
另一份工作。--line-buffer 介于这两者之间:GNU parallel
将打印整行,但允许混合行
不同的工作。
如果tail不是强制性的,您可以使用grep以下方法来实现:
grep "" *.log
Run Code Online (Sandbox Code Playgroud)
这将打印文件名作为每个输出行的前缀。
如果*.log仅扩展到一个文件,输出将中断。在这方面:
grep '' /dev/null *.log
Run Code Online (Sandbox Code Playgroud)