A few sed questions

 
SOLVED
Go to solution
James R. Ferguson
Acclaimed Contributor

Re: A few sed questions

Hi (again) Gemini:

> Dennis: I would suggest you not use sed for something this complicated. awk is much easier to understand.

While 'sed' was not my prefereence either, I would use Perl for the second solution:

# perl -ple 'if (/^install/../^endif/) {print "newline ADDED" if /^endif/}' file

...short, sweet and can be inlined in a shell script.

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: A few sed questions

One more sed question

input
*************************
instal: a b c
ifeq
whatever
endif
********************

I want to do string substition on "install:"
but only if there is a "ifeq" right underneath it... how do I do that?

thank you.


James R. Ferguson
Acclaimed Contributor

Re: A few sed questions

Hi (gemini:

Regarding your newest question, I think you need to look to Perl or 'awk', so:

# perl -nle 'if (/^ifeq/) {$hold=~s/install/NEWINSTALL/};print $hold if defined $hold;$hold=$_' file

...using this input:

# cat input
install: a b c
ifeq
whatever
endif
install: a b c
ofeq
whatever
endif
install: a b c
ifeq
whatever
endif

...the Perl script yields:

NEWINSTALL: a b c
ifeq
whatever
endif
install: a b c
ofeq
whatever
endif
NEWINSTALL: a b c
ifeq
whatever

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: A few sed questions

thanks for your speedy reply.

So, it can not be done in sed, but it can be done in perl right?

no problem, I can use perl in the shell script, i just want to be sure!

Gemini_2
Regular Advisor

Re: A few sed questions

hmm...I submit 10 point, how come it become 0 point.

when you reply, I will submit the right point again.

James R. Ferguson
Acclaimed Contributor

Re: A few sed questions

Hi (again):

Thanks! Glad to help!!!

Regards!

...JRF...
Gemini_2
Regular Advisor

Re: A few sed questions

btw, if you dont mind, can you tell me how you would do it in awk?

James R. Ferguson
Acclaimed Contributor

Re: A few sed questions

Hi Gemini:

> So, it can not be done in sed, but it can be done in perl right?

Well, in fairness, I wouldn't say that it can't be done with 'sed' --- a 'sed' guru probably could, but I'm not that. A good 'sed' guide, including some very advanced handling is here:

http://www.gnu.org/software/sed/manual/sed.html

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: A few sed questions

Hi Gemini:

OK, 'awk' looks like this:

# awk '{if (/^ifeq/) {sub("install","NEWINSTALL",hold)};if (NR>1) {print hold};hold=$0}' file

...with the same example I used for the Perl snippet.

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: A few sed questions

>JRF: awk looks like this:

You are missing the last line:
awk '
{
if (/^ifeq/) {
sub("install","NEWINSTALL",hold)
}
if (NR>1) {print hold}
hold=$0
}
END {print hold}' file