I want to replace a line that contains the matching pattern ForwardX11
in a file with sed, but only want to replace it when the line containing it is the first line found after another line that contains another pattern.
Example:
Host *
# ForwardAgent no
# ForwardX11 no
# ForwardX11Trusted no
# AnotherLine no
Host localhost
ForwardX11 yes
In the example above I only want to replace the line # ForwardX11 no
with Forward yes
because this line is the first one after the line Host *
. But I want to keep the line Forward yes
after the line Host localhost
unchanged.
So far I tried using sed like this:
sed -i "/ForwardX11Trusted/! s/.*ForwardX11.*/ ForwardX11 yes/" /etc/ssh/ssh_config
But it changes the second line too (ForwardX11 after Host localhost).
EDIT 1: It is supposed that I don't know if the line containing the pattern ForwardX11
has #
at beginning or not, and also I dont know if ForwardX11 is set to yes or no.
EDIT 2: It does not have to be done with sed.
CodePudding user response:
Does it have to be sed? Easier (IMO) with awk
awk '
$1 == "Host" {in_block = $2 == "*"}
in_block && $2 == "ForwardX11" {print " ForwardX11 yes"; next}
1
' ssh_config
Host *
# ForwardAgent no
ForwardX11 yes
# ForwardX11Trusted no
# AnotherLine no
Host localhost
ForwardX11 yes
CodePudding user response:
Using sed
$ sed -i.bak '/^Host \*/,/ForwardX11/ s/#\?\(.*X11\) no/\1 yes/' /etc/ssh/sshd_config
Host *
# ForwardAgent no
ForwardX11 yes
# ForwardX11Trusted no
# AnotherLine no
Host localhost
ForwardX11 yes