我正在尝试使用 boost::iostreams 将以下 bash 代码转换为 C++:
#!/usr/bin/bash
(
gzip -cd file1.ext.gz
cat file2.ext
) | grep '^regex' # or sed 's/search/replace/'
我可以打开一个文件并解压缩它:
std::ifstream s("file.ext.gz", std::ios_base::in | std::ios_base::binary);
boost::iostreams::filtering_istreambuf in;
in.push(boost::iostreams::gzip_decompressor());
in.push(s);
然后打开一个未压缩的文件:
std::ifstream s2("file.ext", std::ios_base::in | std::ios_base::binary);
现在我有点卡住了,所以这是我的问题:
1) 连接两个流的 boost::iostreams 解决方案是什么?
2) 如何通过正则表达式过滤器输出结果以模拟 grep/sed?
因此,我想要一个可以复制到 cout 的 istream:
boost::iostream::copy(result, std::cout);
使用Hamigaki 的 concatenate更新完整的解决方案:
/*
* convert the following bash script into C++
*
* #!/bin/bash
* (
* gzip -cd file1.ext.gz
* cat file2.ext
* ) | grep '^filter' | 'sed s/search/replace/g'
*
*/
#include <iostream>
#include <boost/bind.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filter/regex.hpp>
#include <boost/iostreams/filter/grep.hpp>
#include <boost/iostreams/copy.hpp>
// http://hamigaki.sourceforge.jp/hamigaki/iostreams/concatenate.hpp
#include "concatenate.hpp"
namespace io = boost::iostreams;
int main(int argc, char const* argv[])
{
io::file_source file1("file1.ext.gz");
io::file_source file2("file2.ext");
io::gzip_decompressor gzip;
io::regex_filter sed(boost::regex("search"), "replace");
io::grep_filter grep(boost::regex("^filter"));
io::filtering_istreambuf in1(gzip | file1);
io::filtering_istreambuf in2(file2);
io::filtering_istreambuf combined(sed | grep |
hamigaki::iostreams::concatenate(
boost::ref(in1),
boost::ref(in2)
)
);
io::copy(combined, std::cout);
return 0;
}