Re: replace all characters in only a portion of a line

"Tim Chase [email protected] [sed-users]" <[email protected]> Sun, 20 Mar 2016 13:27:52 -0500
Newsgroups gmane.editors.sed.user
Message-ID <[email protected]>
On 2016-03-20 11:52, 'Brian J. Murrell' wrote:
> Let's say I have a file of lines and some of the lines are of the
> form:
> 
> Name: <a first name> <possibly attributions like M.D.>
> 
> Such as:
> 
> Name: Bart Simpson, MD
> 
> and I want to redact the name part only with a 1:1 substitution of
> letters to asterisks so that the result is:
> 
> Name: **** *******, MD
> 
> So effectively I want to do a 's/[A-Za-z]/*/g' only on the portion
> of the line that comes after the ": " and before any ,.
> 
> Is there any way to do this with sed?

it's ugly, but can be done:

tim@localhost$ cat redact.sed
#!/bin/sed -f
# save a pristine copy of the line
h
# delete everything up to the last comma to preserve any title
s/.*,/,/
# if there was a comma we need to put this in the hold buffer for later
t a
# otherwise just redact
b b

:a
# put the attribution in the hold space
x
# remove the attribution from the pristine version
s/,[^,]*$//
# redact the name (and the "Name: ")
s/\S/*/g
# bring back the title
G
# join the two lines
s/\n//
# Don't redact again
b c

:b
# we don't have an attribution
# redact the name (and the "Name: ")
s/\S/*/g

:c
# fix up the "Name: " if we redacted it
s/^....../Name: /

tim@localhost$ printf "Name: Bart Simpson, MD\nName: Homer Simpson\n" | ./redact.sed
Name: **** *******, MD
Name: ***** *******