LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Putting blank line after the search pattern. (https://www.linuxquestions.org/questions/programming-9/putting-blank-line-after-the-search-pattern-671323/)

dina3e 09-20-2008 10:58 PM

Putting blank line after the search pattern.
 
i can make you use of these code to place a new line after the pattern my_word in the file.

sed '/my_word/{x;p;x;}'

But the thing is that how the exchange of the buffers happens ?
and how execution of each line happen or whole fie processed in the buffer. ?

Mr. C. 09-21-2008 03:29 AM

Actually, the code you show would print a newline *before* a line containing my_word:

Code:

$ echo -e 'hello\nmy_word\ngoodbye' | sed '/my_word/{x;p;x;}' 
hello

my_word
goodbye

Sed works by reading and copying the current input line into what it calls "the pattern space" (deleting the newline). Then commands are performed on that pattern space (think of it as a machine register that points to a string). Sed also has a second register called "the hold space" (also a machine register that points to another string).

The x (exchange0 command swaps the hold space with the pattern space..

So your command takes a line, swaps the that line (minus the newline) with the hold space (which is empty). So the pattern space is now empty, and the hold space contains the input line (minus the newline). It them prints (the p command) the contents of the pattern space (empty, so a newline is printed). Then, once again, you swap pattern and hold. Finally, sed's default action is to print the pattern space, so the matched line is printed.

archtoad6 09-21-2008 07:38 AM

Your code will not "place a new line after the pattern my_word in the file", but rather "place a new line after the line containing the pattern my_word in the file". I hope that is what you want, even though it isn't what you say.

Why are you messing w/ the "x" & "p" commands, when "a" (append) will do the job much more simply?:
Code:

sed '/my_word/a\\'

If, OTOH, you really do want to insert a new line directly after the pattern "my_word" in the file (breaking the line it's in at "my_word"), then this should work:
Code:

sed 's,\<my_word\>,&\n,g'
In case you're wondering, from the grep, not sed, man page:
Quote:

The symbols \< and \> respectively match the empty string at the beginning and end of a word.


All times are GMT -5. The time now is 09:05 PM.