将经过 grep STDERR 过滤的文件重定向到文件

问题描述

本文http://burgerbum.com/stderr_pipe.html解释了如何grep STDERR,过滤后的结果在屏幕上回显。

示例: 归档程序 tar 会在 STDERR 上产生很多错误消息,其中一些很重要,而另一些可以忽略。我们只想看到那些表明确实有问题的。

tar -cf /tmp/junk.tar /tmp/real /tmp/fake
tar: Removing leading `/' from member names
tar: /tmp/fake: Cannot stat: No such file or directory
tar: Error exit delayed from prevIoUs errors

为了从 STDERR 中删除 tar: Removing leading '/' from member namestar: Error exit delayed from prevIoUs errors,但保留 tar: /tmp/fake: Cannot stat: No such file or directory,作者建议如下:

(tar -cf /tmp/junk.tar /tmp/real /tmp/fake 3>&1 1>&2 2>&3 | egrep -v "tar: Removing leading|tar: Error exit delayed from prevIoUs errors") 3>&1 1>&2 2>&3

唯一的 STDERR 输出将是:tar: /tmp/fake: Cannot stat: No such file or directory

问题:如何实现相同的结果,但用于回显 => 写入文件

我使用了 tar 示例,因为它是文章的原生代码

但我的真实案例MysqLdump,它生成 STDOUT(我不想弄乱),还生成 STDERR - 我需要过滤并写入文件.

MysqLdump --user=db_username --password=db_password --add-drop-database --host=db_host db_name 2>> '/srv/www/data_appsrv/logs/MysqL_date_ym.log' > '/mnt/backup_srv/PFTLXTKDEV/backup/daily/file_nm_db'

我需要从写入 Warning: Using a password 的 STDERR 中排除 MysqL_date_ym.log 字符串

我尝试了 2>>> 的变体,但没有任何效果

解决方法

在 bash 中,只需:

tar ... 2> >(egrep -v ... >&2)

或归档:

tar ... 2> >(egrep -v ... >the_file.txt )

我认为用 2 个描述符切换 1 没有任何价值,只需使用第 3 个描述符,它已经存在。

( tar ... 2>&1 1>&3 | egrep -v ... ) 3>&1 1>&2

或者您似乎想将 egrep 输出重定向到一个文件。然后这样做:

( tar ... 2>&1 1>&3 | egrep ... >thefile.txt ) 3>&1
# or
( tar ... 2>&1 1>&3 | egrep ... ) 3>&1 1>thefile.txt
# or just
( tar ... 2>&1 1>&3 | egrep ... ) 3>&1 >thefile.txt

或使用该切换:

( tar ... 3>&1 1>&2 2>&3 | egrep ... ) 3>&1 1>thefile.txt 2>&3
( tar ... 3>&1 1>&2 2>&3 | egrep ... >thefile.txt ) 3>&1 2>&3
# it's just:
( tar ... 3>&1 1>&2 2>&3 | egrep ... >thefile.txt ) 2>&1