LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   sed: pattern matching with newlines (https://www.linuxquestions.org/questions/linux-general-1/sed-pattern-matching-with-newlines-706150/)

anjanesh 02-20-2009 05:35 AM

sed: pattern matching with newlines
 
Hi

How do I get sed to read patterns within newlines ?

Code:

sed -i 's|hello.*?world|just-hello|g' *.txt
sed -i 's|hello.*?\n.*?world|just-hello|g' *.txt

Thanks

jschiwal 02-20-2009 06:31 AM

You need to build up more than one line in either the pattern space or the hold space. Then have commands that use `\n' for the newline. The $ metacharacter will match the end of the buffer and not an embedded newline.

Use the N command to append to the pattern space, and H to append to the hold space.

Code:

cat testfile.txt
Hello World.
Hello
World.

Hello cruel world.

Code:

sed '/Hello/{ s/Hello World/Just Hello/;t
                              N;/Hello\nWorld/{N;s//Just\nHello/}
                            }' testfile.txt
Just Hello.
Just
Hello.

Hello cruel world.


syg00 02-20-2009 06:36 AM

Or maybe use a tool better designed for the task - perl, or even awk.


All times are GMT -5. The time now is 08:11 PM.