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

And here's lovely sed(1) tip-of-the-day (replace nth occurrence ...)



So, here's lovely sed(1) tip-of-the day.

Something I quite recently (re?)learned about sed(1).

And it's well in the applicable standard(s)
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html
but GNU sed(1) appears can't be bothered to include this on their
man or info pages for sed.

So ...
s/BRE/replacement/flags
one does that in ed, ex, vi, heck, even vim.
And there are various useful flags.
Among them g - global(ly).
no g flag or the like, only the first match is replaced.
include the g flag, all matches on pattern space or applicable
line(s) are replaced.
But ... what if one wants to replace the nth occurrence, where 1 <= n <= 9 ?
Of course n defaulting to 1 if there's no g flag.
"
The value of flags shall be zero or more of:

n
Substitute for the nth occurrence only of the BRE found within the pattern space.
"
E.g.:
$ echo '1234x6789' | sed -e 's/./5/5'
123456789
$

--
You received this message because you are subscribed to the Google Groups "BerkeleyLUG" group.
To unsubscribe from this group and stop receiving emails from it, send an email to berkeleylug+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/berkeleylug/20200712085244.1370780r84qasmck%40webmail.rawbw.com.