Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Ramakanta Sahoo
Ranch Hand
Posts: 256
Fedora Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!
 
Tim Holloway
Saloon Keeper
Posts: 18304
56
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"/
>
 
Ramakanta Sahoo
Ranch Hand
Posts: 256
Fedora Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 11945
212
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ramakanta Sahoo
Ranch Hand
Posts: 256
Fedora Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have done it like below.
it works like charm. putting it for user reference


 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic