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.

0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.