统一处理压缩和未压缩的文件

作者:David Sinck

在查看日志文件或其他自动压缩和轮换的文件时,能够以统一的方式处理它们非常有用。 以下 bash 函数可以实现这一点

function data_source ()
{
 local F=$1

 # strip the gz if it's there
 F=$(echo $F | perl -pe 's/.gz$//')

 if [[ -f $F ]] ; then
  cat $F
 elif [[ -f $F.gz ]] ; then
  nice gunzip -c $F
 fi
}

现在,当您要处理文件时,可以使用

for file in * ; do
 data_source $file | ...
done

如果您有 bzip2 文件,只需修改 data_source 函数以检查它即可。

加载 Disqus 评论