[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: OT: string manipulation. sed? gawk? other? how?



On 10/11/2011 03:20 PM, John L. Cunningham wrote:
Hi Kent,

On Tue, Oct 11, 2011 at 02:41:10PM -0500, Kent West wrote:
I tried googling my answer, but my google-foo seems to be weak.

I have a text file which may or may not have several similar lines, like so:

The lazy dog ate my lunch.
The dog ate my lunch.
The lazy dog slept all day.
The lazy dog plopped down.

I want to delete all lines starting with "The lazy dog" and replace it
with the single line, "The lazy dog is my favorite." where the first
"The lazy dog" was found in the file.

I want this to work if the file has no occurrences of "The lazy dog"; I
want it to work if it has one occurrence of it. The text above would be
converted to:

The lazy dog is my favorite.
The dog ate my lunch.

I believe I can use
   sed 'The lazy dog'/d
to delete all the lines containing that string, but I don't know how to
put my new line where the first deleted line was.

Thanks for any help.
I would do it in gawk like so:

johnc@infotech:~$ cat text.txt
The lazy dog ate my lunch.
The dog ate my lunch.
The lazy dog slept all day.
The lazy dog plopped down.
johnc@infotech:~$ cat lazydog.awk
/^The lazy dog/{
         if ( count<  1 ){
                 print "The lazy dog is my favorite."
                 count++
                 next
         } else {
                 next
         }
}
{
         print
}
johnc@infotech:~$ gawk -f lazydog.awk text.txt
The lazy dog is my favorite.
The dog ate my lunch.


The above works, although I changed the gawk command to:

gawk -f lazydog.awk text.txt>  outputtext.txt


in order to get a new file with my changes rather than to simply print the results to the display.


comp.unix.shell is a good place to ask these kinds of questions.

John

Thanks!

--
Kent West<*)))><
http://kentwest.blogspot.com
Praise Yah! \o/



Reply to: