J Velvet
J Velvet

Reputation: 85

How to comment out first occurrence of line after an original matching line bash

I'm writing a bash script for a homework assignment that finds the first occurrence of this line: "cin >>n;" after int main() in a c++ file and comments it out.

The problem is that "cin >> n" may or may not exist inside of main, and main can have any size of lines so I have to search for main() and then search again from main for "cin >> n;" after finding main. I assume sed can be used for this but I only know how to search for one thing at a time.

Here's and example of an input file:

#include <studio.h>
void hi()
{
  int n;
  cin >> n; //I dont want to be commented out
  prinf("hi");
}

int main()
{
  int n;
  bool foo = false;
  cin >> n; //I want to be commented out
  if(!foo){
    cin >> n; //I dont want to be commented out
  }  
}

void supp(){
  cin >> n; //I dont want to be commented out
}

Upvotes: 0

Views: 71

Answers (1)

Pierre Fran&#231;ois
Pierre Fran&#231;ois

Reputation: 6073

Assuming your file is correctly indented as shown above and is called prog.c, you can issue:

sed '/^int main/,$s|^  \( *cin >>.*\)|//&\n§§|' prog.c |
sed '/^§§/,$s|//\( *cin >> n\)|  \1|' |
sed '/^§§/d'

The idea is to comment out all the lines, between int main() and the end of the file, containing cin >> n and adding a line containing §§ (could be something else) just after each matched line.

The second step is to remove from the comments all the lines having cin >> n after the first occurence of §§ until the end of the main() function.

Once this is done, all the lines containing §§ must be removed.

Edit:

I found a much easier solution, after thinking a lot:

sed '/^int main/,/^ *cin >> n/s|^  \( *cin >>.*\)|//\1|' prog.c

The idea behind this second solution is to comment out all the lines having cin >> n from the line where int main() stays, up to the line with the first occurrence of cin >> n. As simple as that. Sorry that I didn't see this before.

Demo

This is the output of both solutions above:

#include <studio.h>
void hi()
{
  int n;
  cin >> n; //I dont want to be commented out
  prinf("hi");
}

int main()
{
  int n;
  bool foo = false;
//  cin >> n; //I want to be commented out
  if(!foo){
      cin >> n; //I dont want to be commented out
  }  
}

void supp(){
  cin >> n; //I dont want to be commented out
}

Upvotes: 1

Related Questions