The following awk
script can do what you ask:
echo 'int var1;
int var2;
int var3;
int var4;
int var5;
' | awk '
/^int var2;$/ {
count = 3;
}
{
if (count > 0) {
$0 = "//"$0;
count = count - 1;
};
print;
}'
This outputs:
int var1;
//int var2;
//int var3;
//int var4;
int var5;
The way it works is relatively simple. The counter variable c
decides how many lines are left to comment. It starts as 0 but when you find a specific pattern, it gets set to 3.
Then, it starts counting down, affecting that many lines (including the one that set it to 3).
If you're not that worried about readability, you can use the shorter:
awk '/^int var2;$/{c=3}{if(c>0){$0="//"$0;c=c-1};print}'
Be aware that the count will be reset whenever the pattern is found. This seems to be the logical way of handling:
int var1; ----> int var1;
int var2; //int var2;
int var3; //int var3;
int var2; //int var2;
int var3; //int var3;
int var4; //int var4;
int var5; int var5;
If that's not what you wanted, replace count = 3;
with if (count == 0) {count = 3;};
or use:
awk '/^int var2;$/{if(c==0){c=3}}{if(c>0){$0="//"$0;c=c-1};print}'
for the compact version.