2

In bash, how do I search for the following string in a file ~/.netrc and delete that line plus the next two lines if found:

machine api.mydomain.com

Example is:

machine api.mydomain.com
   user foo
   password bar

It should delete all three lines, but I can't match user and password since those are unknown. The only fixed value is machine api.mydomain.com.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Justin
  • 42,716
  • 77
  • 201
  • 296

2 Answers2

4

Try:

sed -i '' '/^machine api.mydomain.com$/{N;N;d;}' ~/.netrc

When this finds the line machine api.mydomain.com, it reads in two more lines and then deletes them all. Other lines pass through unchanged.

For GNU sed, the argument to -i is optional. For OSX (BSD) sed, the argument is required but is allowed to be empty as shown above.

John1024
  • 109,961
  • 14
  • 137
  • 171
2

Let's google it together - sed or awk: delete n lines following a pattern

So, the answer is sed -e '/machine api.mydomain.com/,+2d' ~/.netrc. Add -i flag if changes need to be done in place.

Community
  • 1
  • 1
  • Does this work on OS X? Getting `sed: 1: "/machine api.mydomain.c ...": expected context address` I need this to work on standard Linux and OS X. – Justin May 03 '15 at 21:57
  • @Justin For OSX, add `-i` then space then `''`. In other words, use `sed -i '' -e '/machine api.mydomain.com/,+2d' ~/.netrc` – John1024 May 03 '15 at 21:59
  • Still not working. `sed -i '' -e '/machine api.mydomain.com/,+2d' ~/.netrc` sed: 1: "/machine api.mydomain.c ...": expected context address – Justin May 03 '15 at 22:02
  • @Justin __"expected context address"__: That is a different problem. The fancy range (`+2`) is not supported by OSX/BSD. I just wrote an answer that avoids that. – John1024 May 03 '15 at 22:30