2011-04-19

Search for a string and print N following lines.

A litte C++ code snippet to filter some text from standard input to standard output while keeping only N-1 lines following a search string.

#include <sstream>
#include <iostream>
#include <string>
/*
 * If standard input contains a line with the string argv[1],
 * then print up to argv[2] lines, including the one found,
 * on standard output.
 * Dedicated to the public domain.
 * @author Peter Jansson
 * @date 2011-04-19
 */
int main(int argc,char** argv)
{
   using namespace std;
   const string argv1( argv[1] );
   istringstream iss( argv[2] );
   int N(0);
   iss >> N;
   for(string line; getline( cin, line );)
   {
      if( line.find( argv1 ) != string::npos )
      {
         for( ; N > 0 && cin; N-- )
         {
            cout << line << '\n';
            getline( cin, line );
         }
         break;
      }
   }
   return 0;
}

0 kommentarer:

Post a Comment