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

3 views
Skip to first unread message

Michael Paoli

unread,
Jul 12, 2020, 11:52:46 AM7/12/20
to BerkeleyLUG
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
$

Reply all
Reply to author
Forward
0 new messages