File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Linux / UNIX and the fly likes [SED]How to replace a line with newone if a pattern matches Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Engineering » Linux / UNIX
Bookmark "[SED]How to replace a line with newone if a pattern matches" Watch "[SED]How to replace a line with newone if a pattern matches" New topic
Author

[SED]How to replace a line with newone if a pattern matches

Ramakanta Sahoo
Ranch Hand

Joined: Aug 23, 2008
Posts: 247

I have a line in file myfile.txt and i want to replace it with another if a pattern matches exactly.

Line:

match pattern:


Replace line:

Please help!!


Regards, Ricky
Oracle Weblogic 10g Certified Expert
TechPaste.Com
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 15632
    
  15

sed can delete and insert lines and do so based on pattern matches. But a simple replacement ought to be all that your example needs;

s/<ENTITY dbname "(\w+)"/><ENTITY dname "HOSTNAME"/
>


Customer surveys are for companies who didn't pay proper attention to begin with.
Ramakanta Sahoo
Ranch Hand

Joined: Aug 23, 2008
Posts: 247

Tim Holloway wrote:sed can delete and insert lines and do so based on pattern matches. But a simple replacement ought to be all that your example needs;

s/<ENTITY dbname "(\w+)"/><ENTITY dname "HOSTNAME"/
>


I tried


This does not work!!
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11278
    
  59

You will need to look up regular expressions if you want to work with these sorts of issues. Tim's solution is 99% there, and a simple look at a the regular expression he used for word matching shows that the problem is with the definition of a word. He used "\w", which matches on "A-Z", "a-z", and "0-9". Note that this is slightly different in Perl, which also includes "_" in it's definition of what a word is.

Knowing this, I can make a far more verbose attempt in sed:



Note that I used the capital "-E" for extended (modern) regular expressions. Depending on your host's implementation of sed this may not be necessary for you.


The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
Ramakanta Sahoo
Ranch Hand

Joined: Aug 23, 2008
Posts: 247

I have done it like below.
it works like charm. putting it for user reference


 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: [SED]How to replace a line with newone if a pattern matches
 
Similar Threads
Doubt with replace all
Declaring and Ordering filters
Servlet mapping
ant replaceregexp/multi-line matching problems
Help replacing characters using XSL