我想将进程的每个新的 stderr 行重定向到一系列文本文件。我如何在 bash 中做到这一点?
我努力了:
myProcess 2>&1 >/dev/null | grep 'Parsed' > parsed.txt | tail -f parsed.txt > line.`date +%s`.txt
您需要读取输出的每一行并将其显式重定向到一个新文件。
myProcess 2>&1 >/dev/null | grep 'Parsed' | tee parsed.txt | while IFS= read -r line; do
echo "$line" >> line.$(date +%s).txt
done
还要注意使用tee
将每一行从文件写入grep
文件parsed.txt
以及while
将每一行重定向到每秒文件的循环。
Another variant:
myprocess 2> >(sed 's/.*/echo "&">>$(date +%s)/e;d')
Needs gnu sed & bash should have support for process redirection.
#!/bin/bash
function splitter {
grep 'Parsed' |
while read L; do
echo "$L" >> `date +%s`
done
}
myProcess 2> >( splitter ) > /dev/null
两条评论:
... | grep 'Parsed' > parsed.txt
您将所有grep
输出重定向到parsed.txt
,因此没有任何东西可以输入下一个管道。此外,tail
从管道或文件读取,而不是同时读取。
如果您希望相同的输出转到您需要的多个文件tee
:
myProcess 2>&1 >/dev/null | grep 'Parsed' | tee f1.txt | tee f2.txt > f3.txt
问题是 OS X 终端不返回毫秒,每个时间戳文件都有很多行
我找到的解决方案是这样的:我从http://cr.yp.to/daemontools/tai64n
安装了 deamontools 。
html
获取以下实用程序:
tai64n
tai64nlocal
使用命令:
echo | tai64n | tai64nlocal
它返回:
2013-07-03 10:34:41.756602500
所以我的最终脚本是:
#!/bin/bash
function splitter {
grep 'Parsed' |
while read L; do
t=`echo | tai64n | tai64nlocal`
echo "$L" >> parse."$t".txt
done
}
myProcess 2> >( splitter ) > /dev/null
对于每个 stderr 新行。
谢谢大家的帮助。
这是我的第一个问题,结果很好