LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Find pattern and comment out 2 lines after it (https://www.linuxquestions.org/questions/linux-newbie-8/find-pattern-and-comment-out-2-lines-after-it-837981/)

ariszlo 10-14-2010 03:34 AM

Find pattern and comment out 2 lines after it
 
How do yo find a pattern with sed or awk and then:
- add a # at the beginning of the line containing it
- and add a # at the beginning of the following 2 lines, too?

Say, I want to comment out the line containing "which 0launch" and the two lines following it:

if [ -x "`which 0launch`" ]; then
exec 0launch http://rox.sourceforge.net/2005/interfaces/ROX-Filer -S
fi

Expected result:

#if [ -x "`which 0launch`" ]; then
# exec 0launch http://rox.sourceforge.net/2005/interfaces/ROX-Filer -S
#fi

I need this because I do not want to comment out every line containing "fi", just the "fi" of this specific if statement.

grail 10-14-2010 04:15 AM

Well I will assume you would know how to place a # at the front of the single line. To do the 2 following lines you can either use a counter or getline

jschiwal 10-14-2010 04:36 AM

In sed you can use /<pattern>/ to find a match

sed '/which 0launch/,+2s/^/#/' file >newfile

Or
sed '/which 0launch/,/^fi/s/^#/' file >newfile
Which will work over a variable range of lines. I'm making an assumption that any subsequent if .. fi regions inside the region to comment will be indented.

ariszlo 10-14-2010 05:37 AM

Quote:

Originally Posted by jschiwal (Post 4126940)
sed '/which 0launch/,+2s/^/#/' file >newfile
sed '/which 0launch/,/^fi/s/^/#/' file >newfile

Thank you very much, both work fine. :)


All times are GMT -5. The time now is 11:32 AM.