0

我得到了这些文件:

bonds.txt.gz
bonds_201307.txt.gz
bonds_201308.txt.gz
bonds_201309.txt.gz
bonds_201310.txt.gz
bonds_201311.txt.gz
bonds_201312.txt.gz

我有一个 for 循环来遍历文件,解压缩它们,然后用 grep 找到一个字符串:

for f in `ls *.txt.gz`; do echo $f; zcat $f | grep MYBOND; done

如果我运行它,我会得到以下信息:

bonds.txt.gz
zcat: bonds.txt.gz.gz: No such file or directory
bonds_201307.txt.gz
zcat: bonds_201307.txt.gz.gz: No such file or directory
bonds_201308.txt.gz
zcat: bonds_201308.txt.gz.gz: No such file or directory
bonds_201309.txt.gz
zcat: bonds_201309.txt.gz.gz: No such file or directory
bonds_201310.txt.gz
zcat: bonds_201310.txt.gz.gz: No such file or directory
bonds_201311.txt.gz
zcat: bonds_201311.txt.gz.gz: No such file or directory
bonds_201312.txt.gz
zcat: bonds_201312.txt.gz.gz: No such file or directory

似乎 zcat 正在用额外的 .gz 扩展文件名但是当我尝试从命令行 zcat 文件时它没有这样做,只是拿起提供的文件名并完成它的工作。为什么在循环中调用时会发生这种情况?

我知道我可以通过使用 zgrep 或 find 来达到同样的效果,但仍然对了解 zcat 的这种行为感兴趣。谢谢!

4

1 回答 1

4

I tried your script, there is no issue, but if I set alias ls='ls --color=always', I will have the same issue

maybe your ls returns some hidden characters like color code
can you try

for f in `\ls *.txt.gz`

but you could have used

for f in *.txt.gz instead of

for f in `ls *.txt.gz`

and if your system has zgrep, you could use zgrep MYBOND $f instead of zcat $f | grep MYBOND

The code will be like this:

for f in *.txt.gz; do echo "$f"; zgrep MYBOND "$f"; done
于 2014-01-16T09:13:17.753 回答