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.

2 Answers 2

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.

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.

4
  • 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 3, 2015 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 3, 2015 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 3, 2015 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 3, 2015 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.