Reputation: 75
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
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.
/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