for循环中的zcat文件名扩展

时间:2014-01-16 09:00:58

标签: bash unix zcat

我收到了这些文件:

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的这种行为。 谢谢!

1 个答案:

答案 0 :(得分:4)

我尝试了你的脚本,没有问题,但如果我设置alias ls='ls --color=always',我会遇到同样的问题

也许你的ls会返回一些隐藏的字符,比如颜色代码
你能试试吗

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

但你可以使用

for f in *.txt.gz而不是

for f in `ls *.txt.gz`

如果您的系统有zgrep,则可以使用zgrep MYBOND $f代替zcat $f | grep MYBOND

代码将是这样的:

for f in *.txt.gz; do echo "$f"; zgrep MYBOND "$f"; done