[SOLVED] use sed to find string pattern and delete subsequent characters
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
For example, is it: 'find the first "#" and delete everything after "#" plus 2 characters'?
Your code finds the pattern: '"#", followed by any character, then any number of characters'
Try this:
Code:
sed 's/\(#..\).*/\1/' filename
This uses a backreference to capture "#" plus any 2 characters (as part of the total matched expression), and re-insert that pattern in place of the total match.
@PMP: The first .* and the g option are not needed (but don't do any harm for the task at hand).
@pixellany: I would have chosen your example, but the "missing" first part (everything up to the #) can be confusing if you are not familiar with sed. As long as the first .* in PMP's example is part of the back referencing all is ok.
@PMP - I think what pixellany is referring to is if you change the pattern to have anymore hashes (#) in it then yours will be a little greedy. Try this string:
I was in error!! The confusion was in the fact that the backreference in PMP's solution was replacing everything on the first part of line, whereas mine replaces on what starts with "#..". It was not obvious at a glance that they were doing the same thing.
In PMP's solution, why does the "#" have to be escaped?
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.