14

I'm trying to cat a bunch of files, some of which may not exist. Now that's ok if some of them don't exist, but I don't want cat to return an error in this case, if possible. Here's my call:

zcat *_max.rpt.gz *_min.rpt.gz | gzip > temp.rpt.gz

When this command is run, either a bunch of files matching *_max.rpt.gz will exist, or *_min.rpt.gz will exist. If the other doesn't exist, I don't care, I just want to concatenate what I can. But I'm getting an error message which stops the rest of my code from running.

Anything I can do? Thanks.

4

5 回答 5

29

只需将 stderr 重定向到 /dev/null:

cat file1 file2 .... 2>/dev/null

如果一个或多个文件不存在,则 cat 将给出一个错误,该错误将转到 /dev/null ,您将获得所需的结果。

于 2012-10-10T22:02:07.580 回答
7

[ -f file.txt ] && cat file.txt

于 2020-09-11T17:10:39.213 回答
6
grep -hs ^ file1 file2 ....

不像 cat 有零返回码。选项 -h 禁用文件名打印,选项 -s 禁用文件错误报告,^ 匹配所有行。

于 2018-12-17T15:19:58.737 回答
1
zcat `ls *.rpt.gz | grep -E '_(max|min)\.rpt\.gz$'` | gzip > temp.rpt.gz

有点hack,但是shell也是如此:-P

于 2012-10-10T22:03:16.413 回答
0

您可以附加|| True到命令以使退出代码静音。

于 2020-08-27T09:55:49.317 回答