Need sed to do something which sounds simple

Manish Jain invalid.pointer at gmail.com
Fri May 29 13:00:30 UTC 2009


Paul Schmehl wrote:
> --On Thursday, May 28, 2009 07:48:36 -0500 Manish Jain 
> <invalid.pointer at gmail.com> wrote:
> 
>>
>>
>> Hi,
>>
>> I need sed to do something which sounds simple, but I can't figure out
>> the right command. All I need to do is insert a blank after a '}' at the
>> end of a line if the next line begins immediately afterwards (i.e. with
>> no blank line between).
>>
>> //abc.cpp :
>> int myclass::fx(int * arg)
>> {
>>         if(! (isValid()))
>>         {
>>                 return -1;
>>         }
>>         return ptr->fx(arg);
>> }
>>
>> //what-i-want.cpp :
>> int myclass::fx(int * arg)
>> {
>>         if(! (isValid()))
>>         {
>>                 return -1;
>>         }
>>
>>         return ptr->fx(arg);
>> }
>>
>> The commands I have tried are :
>>
>> i)
>> sed -e 's/\(}$\)\n\(^[[:space:]]*[[:alpha:]]\+\)/\1\n\n\2/' \
>> <abc.cpp  >what-i-want.cpp
>>
>> ii)
>> sed -e 's/\(}$\)\(^[[:space:]]*[[:alpha:]]\+\)/\1\n\2/' \
>> <abc.cpp  >what-i-want.cpp
>>
>> but obviously neither works, which is why posting this message.
>>
>> Can anybody please tell me what the correct command would be like ?
>>
> 
> Seems like this would work to add a space only to lines where the next 
> line only has a new line :
> 
> sed  '  /\}$/ { N /}$\n\n/ { s/\}$\n/\} $\n/} } ' file
> 
> If the possibility exists that the new line might have spaces as well, 
> you could do this:
> 
> sed  '  /\}$/ { N /}$\n\n/ { s/\}$\n[ ]?/\} $\n/} } '
> 
> Note: I haven't tested this, so it may require some modification.  Read 
> this page on dealing with multiple lines in sed to gain further 
> understanding - http://www.grymoire.com/Unix/Sed.html
>


Hello Paul,

After reading the sed document, the following worked for me :


sed '
/}$/ {
N
s/}\n\([[:space:]]\+\)\n*/}\n\n\1/
}' <abc.cpp  >what-i-want.cpp


This keeps the indentation intact.

Thanks for the help &
-- 
Regards
Manish Jain
invalid.pointer at gmail.com
+91-96500-10329

Laast year I kudn't spell Software Engineer. Now I are won.


More information about the freebsd-questions mailing list