Operating System - HP-UX
1822002 Members
3902 Online
109639 Solutions
New Discussion юеВ

Re: Can sed scripts insert new lines?

 
Paul Young_4
New Member

Can sed scripts insert new lines?

hi,

I'm trying to replace a combination of two lines with some text using sed. I have a problem when the first line is duplicated as I need sed to insert a newline. I have tried using \n and \\n to insert the newline in place of my obviously wrong NEWLINE in my attempt below, but it still does not work.

Can anyone help me?
Thanks.

Paul.


#!/bin/sed -f

/FirstLine/ {
# Read in the next line of input.
N

# Remove Duplicate.
/FirstLine\n\(.*FirstLine\)/ {
#####################################
# The Following Line does not work. #
#####################################
s/FirstLine\n\(.*FirstLine\)/NEWLINE\1/

# Read in the next line of input.
N
}

# Replace the match.
s/FirstLine\n.*SecondLine/PERFECT MATCH/

}
6 REPLIES 6
Massimo Bianchi
Honored Contributor

Re: Can sed scripts insert new lines?

Hi,
here is a little suggestion:

Add new line at the middle using some pattern

# sed 's/111/111Z/g' test | tr "111Z" "111\012]" add newline after "111"


I don't know if it is applicable but it show how to put the newline, using "tr".


HTH,
Massimo
rachel_11
Advisor

Re: Can sed scripts insert new lines?

This is a reply to the tr suggestion.

The tr command does not compare strings, but corresponding position letters in a string.

In the example every "Z" will be replaced with "\012", (every 1 will be replaced with 1)

Not sure it is the desired result
vasundhara
Frequent Advisor

Re: Can sed scripts insert new lines?

Hi,

Don't know if you have tried this also...

Give back slash for \n at s/FirstLine\n\(.*FirstLine\)/NEWLINE\1/ ???

Try
s/FirstLine\\n\(.*FirstLine\)/NEWLINE\1/ .

Regards
VJ.
F. X. de Montgolfier
Valued Contributor

Re: Can sed scripts insert new lines?

Hi,

<>
gives the attached script to print only one version of any duplicate line
in a file.

BTW, sed.sourceforge.net is a good source for sed scripts

Cheers,

FiX
Paul Young_4
New Member

Re: Can sed scripts insert new lines?

Thankyou all for your replies. To solve my problem i used your solution (thanks to Massimo and Rachel).

Then i read the link that Fix gave me and I got the nice way i was hoping to do it (so I could use sed for everything).

To put a new line in the replacement string you backslash the line and continue on the following so my line would be:

s/FirstLine\n\(.*FirstLine\)/\1/

Paul.
Paul Young_4
New Member

Re: Can sed scripts insert new lines?

My last reply didnt work because there must be a formatter here who doesnt like free line space - where you see CR there should be a Carriage Return.

s/FirstLine\n\(.*FirstLine\)/\CR
\1/

Paul.