user3151788
user3151788

Reputation: 75

how to comment out the first occurrence with sed

I’m trying to comment out a line in a config file with sed and have an issue.

I am using sed –i '/GV()/s/^/#/' filename

and it works, but it comments out all occurrences of GV() in the file. I only want to comment out the first occurrence.

Any idea how I can do this with sed?

Thanks

Upvotes: 0

Views: 346

Answers (3)

John1024
John1024

Reputation: 113964

For this problem, awk is a natural tool. Consider this test file:

$ cat file
one
GV()
GV()

Then, using awk:

$ awk '/GV()/ && !f {print "#"$0; f=1; next} 1' file
one
#GV()
GV()

The above comments out a line containing GV() only if no such line has been seen before. The variable f keeps track of whether GV() has been seen before.

How it works

  • /GV()/ && !f {print "#"$0; f=1; next}

    /GV()/ && !f is a condition: the statements which follow in braces, {...}, are only executed if the condition is true. It is true only if the line contains GV() and if f is false, meaning that we haven't seen such a line before. In that case, we (a) comment out the line, print "#"$0, (b) set f to true: f=1, and (c) skip the rest of the commands and start over on the next line.

  • 1

    This awk's cryptic shorthand for print the line.

Upvotes: 0

RenBrian
RenBrian

Reputation: 92

sed -e '1,/GV()/s/GV()/#GV()/' filename

Upvotes: 1

Cyrus
Cyrus

Reputation: 88899

With GNU sed:

sed -i '/GV()/{s/.*/#&/;:A;n;bA}' file

Upvotes: 1

Related Questions