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?