Issue
I know I can run commands against a match in sed
like so:
$ cat file
line1
line2
line3
line4
$ sed -e "/^line2/ s/^/# /" file
line1
# line2
line3
line4
Is it possible to run multiple commands, say s/^/#/
and s/$/ # invalid/
on the same match?
I tried adding them both but I get an error:
$ sed -e "/^line2/ s/^/# / s/$/ # /" file
sed: -e expression #1, char 18: unknown option to `s'
I tried using ;
but that seems to discard the initial match and execute on every line in the input:
$ sed -e "/^line2/ s/^/# / ; s/$/ # /" file
line1 #
# line2 #
line3 #
line4 #
Solution
EDIT2: In case you are looking very specifically to execute multiple statements when a condition has met then you could use {..}
block statements as follows.(Just saw @Tiw suggested same thing in comments too.)
sed '/^line2/ {s/^/#/; s/$/ # invalid/}' Input_file
EDIT: Adding 1 more solution with sed
here. (I am simply taking line
which is starting with line2
in a memory buffer \1
then simply while putting substituted/new_value adding #
before it and appending # invalid
after it)
sed '/^line2/s/\(.*\)/# \1 # invalid/' Input_file
Could you please try following.
sed "/^line2/ s/^/# /;/^line2/s/$/ # invalid/" Input_file
What is happening in your attempt, you are simply doing substitution which is happening on each line irrespective of either it starts from line2
or not, so when you give that condition before substitution it should work then.
Answered By - RavinderSingh13