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

Re: Delete all after a pattern



On Sat 31 Aug 2019 at 09:02:07 (-0400), Roberto C. Sánchez wrote:
> On Sat, Aug 31, 2019 at 08:39:56AM -0400, The Wanderer wrote:
> > On 2019-08-31 at 07:58, Roberto C. Sánchez wrote:
> > > On Sat, Aug 31, 2019 at 01:49:20PM +0200, Computer Planet wrote:
> > > 
> > >> Hi guys! Is It possible, with "sed" erase all after a pattern? I'm
> > >> trying in all way but I can't... I'd like to erase all after the
> > >> pattern "config=" but only in the same line, regardless of where it
> > >> is located inside in a file.
> > >> 
> > >> Can somebody help me please? Thank in advance for reply.
> > >> 
> > >> e.g.: after "config=" erase all until the end of the line
> > > 
> > > Something like this:
> > > 
> > > sed -E 's/(.*config=).*/\1/'
> > 
> > Or perhaps
> > 
> > sed 's/config=.*$/config=/g'
> > 
> > ?
> > 
> > Less elegant and idiomatic, but could also get the job done.
> > 
> OK.
> 
> > The 'g' at the end is in case there can be multiple occurrences of
> > 'config=' in a single file, so that sed won't stop after the first one
> > it finds.
> > 
> That's not how 'g' works.  It is global replace of all occurences of the
> patter in the pattern space.  By default, sed operates one line at a
> time so the replacement will happen on every line that matches the
> pattern even without the 'g'.
> 
> $  cat ~/test.txt 
> Test config=foo
> Test config=foo
> Test config=foo
> $  sed 's/config=.*$/config=/g' ~/test.txt 
> Test config=
> Test config=
> Test config=
> $  sed 's/config=.*$/config=/' ~/test.txt 
> Test config=
> Test config=
> Test config=
> 
> Since the desired effect is "replace everything to the end of the line"
> then the 'g' has no practical effect.  It is not really possible to have
> multiple patterns match to the end of the line, unless you were trying
> to do some form of relucant matching.

I wasn't aware that sed could do reluctant (or non-greedy) matching.
IOW there's no .*? pattern like there is in grep. I've always used
[^… … …] patterns instead where possible, or switched to python
(perl in the past).

As for g, yes, it's intended for things like

$ sed -e 's/ 1/ /;' <<<'9 10 11 12 13'
9 0 11 12 13
$ sed -e 's/ 1/ /g;' <<<'9 10 11 12 13'
9 0 1 2 3
$ 

Cheers,
David.


Reply to: