I want to search for a line that contains log4j
and take 7 lines before and 3 lines after the match.
grep -B7 -A3 "log4j" web.xml
After that I want to add comment tags before this paragraph and after it.
<!--
paragraph that i found by grep
-->
I wrote this script bellow:
search=`find . -name 'web.xml'`
text=`grep -B7 -A3 "log4j" $search`
sed -i "/$text/c $newparagraph" $search
It's not working. Is there any way to just add comment symbol not replace the paragraph?
What I want to the script to do:
- search for the paragraph
- append
- append --> at the end
Edit: This is the paragraph that am trying manipulate :
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listenerclass>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
This paragraph is part of many paragraphs! I want make it like this:
<!--
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listenerclass>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
-->
This would be better done with an XML library, but here it is in sed...
Sed has
i
anda
commands for inserting and appending lines. I think the following script will help.The first part, `sed -n '/log4jConfigLocation/=' will get the line numbers that have 'log4jConfigLocation'. The next part uses those line numbers in two commands: insert a line 1 line above, and append a line 8 lines below.
There is a better way using sed's hold buffer, but I'm not familiar enough with it; if you're interested, you can see this guide. Ultimately, though, if you're going to be working with this type of stuff regularly, you should check out XMLStarlet.