0

I'm trying to find and replace specific string with sed command but when I run the command nothing seems to be happening.

FIND:

LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

REPLACE WITH:

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

FILE CONTENT

hello
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
bye

COMMAND

$ sed -i 's/LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined/LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined/g' /etc/apache2/apache2.conf

I looked into How do I escape double and single quotes in SED? (bash) but cannot workout what the problem is.

Community
  • 1
  • 1
BentCoder
  • 12,257
  • 22
  • 93
  • 165

1 Answers1

1

Your file contains backslashes before quotes. Your sed regexp does likewise but in the sed case those are escape chars when you need literals. You need to escape the backslashes to make them literal, e.g.:

...\\"%r\\"..

See:

$ sed 's/LogFormat "%h %l %u %t \\"%r\\" %>s %O \\"%{Referer}i\\" \\"%{User-Agent}i\\"" combined/LogFormat "%{X-Forwarded-For}i %l %u %t \\"%r\\" %>s %b \\"%{Referer}i\\" \\"%{User-Agent}i\\"" combined/g' file
hello
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
bye

but consider using capture groups instead of duplicating all the text in the substitution:

$ sed 's/\(LogFormat "\)%h\( %l %u %t \\"%r\\" %>s %\)O\( \\"%{Referer}i\\" \\"%{User-Agent}i\\"" combined\)/\1%{X-Forwarded-For}i\2b\3/g' file
hello
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
bye
Ed Morton
  • 188,023
  • 17
  • 78
  • 185