0

I have file that has the following lines in it in a file called test.txt;

volumes:
  data:
    driver: test

I want to change them to;

volumes:
  # data:
    # driver: test

But when I use the following command it seems to not work:

sed 's/  data:\n    driver: test/  # data:\n   # driver: test/' test.txt

What am I doing wrong?

e0k
  • 6,961
  • 2
  • 23
  • 30

1 Answers1

0

You are trying to match a pattern that spans multiple lines. sed tries to match the regex to each line. Try using a separate pattern for each line:

sed 's/^  data:/  # data:/;s/^    driver: test/    # driver: test/' test.txt

There are two s commands, separated by a semicolon ;. You seem to need to require a specific number of spaces (2 for the data line, 4 for driver), so I left that the same. Notice the use of ^ to anchor the regex to the beginning of the line.


Suppose your input file test.txt is now:

volumes:
  data:
    driver: test
volumes:
  data:
    driver: test

To only replace the first occurrence of the driver: test pattern (but all occurrences of the data: pattern), try something like:

sed 's/^  data:/  # data:/;0,/^    driver: test/s//    # driver: test/' test.txt

This will only work with GNU sed. The result is:

volumes:
  # data:
    # driver: test
volumes:
  # data:
    driver: test

To only match the first occurrence of both, try

sed '0,/^  data:/s//  # data:/;0,/^    driver: test/s//    # driver: test/' test.txt

which gives

volumes:
  # data:
    # driver: test
volumes:
  data:
    driver: test

See also How to use sed to replace only the first occurrence in a file?

e0k
  • 6,961
  • 2
  • 23
  • 30
  • That work, well somewhat. I neglected to mention that driver: test is mentioned multiple times. when I use the above command, it changes all the instances of it. I only need to make a change to the first one. volumes: data: driver: test storage driver: test changes to volumes: data: # driver: test storage # driver: test – user4380125 May 09 '18 at 21:47
  • That is a significant change to your question. For that, I'll refer you to [How to use sed to replace only the first occurrence in a file?](https://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file) – e0k May 09 '18 at 21:53