The question asks for solutions using sed
, but if that's not a hard requirement then there is another option which might be a wiser choice.
The accepted answer suggests sed -i
and describes it as replacing the file in-place, but -i
doesn't really do that and instead does the equivalent of sed pattern file > tmp; mv tmp file
, preserving ownership and modes. This is not ideal in many circumstances. In general I do not recommend running sed -i
non-interactively as part of an automatic process--it's like setting a bomb with a fuse of an unknown length. Sooner or later it will blow up on someone.
To actually edit a file "in place" and replace a line matching a pattern with some other content you would be well served to use an actual text editor. This is how it's done with ed
, the standard text editor.
printf '%s\n' '/TEXT_TO_BE_REPLACED/' d i 'This line is removed by the admin' . w q | \
ed -s /tmp/foo > /dev/null
Note that this only replaces the first matching line, which is what the question implied was wanted. This is a material difference from most of the other answers.
That disadvantage aside, there are some advantages to using ed
over sed
:
- You can replace the match with one or multiple lines without any extra effort.
- The replacement text can be arbitrarily complex without needing any escaping to protect it.
- Most importantly, the original file is opened, modified, and saved. A copy is not made.
How it works
How it works:
- printf will use its first argument as a format string and print each of its other arguments using that format, effectively meaning that each argument to printf becomes a line of output, which is all sent to
ed
on stdin.
- The first line is a regex pattern match which causes ed to move its notion of "the current line" forward to the first line that matches (if there is no match the current line is set to the last line of the file).
- The next is the
d
command which instructs ed
to delete the entire current line.
- After that is the
i
command which puts ed
into insert mode;
- after that all subsequent lines entered are written to the current line (or additional lines if there are any embedded newlines). This means you can expand a variable (e.g.
"$foo"
) containing multiple lines here and it will insert all of them.
- Insert mode ends when
ed
sees a line consisting of .
- The
w
command writes the content of the file to disk, and
- the
q
command quits.
- The
ed
command is given the -s
switch, putting it into silent mode so it doesn't echo any information as it runs,
- the file to be edited is given as an argument to
ed
,
- and, finally, stdout is thrown away to prevent the line matching the regex from being printed.
Some Unix-like systems may (inappropriately) ship without an ed
installed, but may still ship with an ex
; if so you can simply use it instead. If have vim
but no ex
or ed
you can use vim -e
instead. If you have only standard vi
but no ex
or ed
, complain to your sysadmin.