Wednesday, October 5, 2022

[SOLVED] `sed` works, but `sed -i` returns an error

Issue

This line works:

sed -r -e 's/^([^#a-z]+)localhost/\1hostname.domain hostname localhost/' /etc/hosts

But adding the itty option "i":

sed -ir -e 's/^([^#a-z]+)localhost/\1hostname.domain hostname localhost/' /etc/hosts

Results in:

sed: -e expression #1, char 60: invalid reference \1 on `s' command's RHS

Can someone tell me what's going on??


Solution

You've turned off the -r (extended syntax) option, because what you append to -i isn't more options, but an optional backup suffix. From the manpage:

-i[SUFFIX], --in-place[=SUFFIX]

   edit files in place (makes backup if extension supplied)

So just separate them:

sed -i -r -e 's/^([^#a-z]+)localhost/\1hostname.domain hostname localhost/' /etc/hosts


Answered By - T.J. Crowder
Answer Checked By - Gilberto Lyons (WPSolving Admin)