I'm interested in changing a birth date in a text file to a different date of 11/14/46. I want to do this without having to know the previous birth date and instead be able to search generically. I know the person's name that the birth date is associated with, so I can use that to make the substitution
I've tried this:
sed "s/^PersonsName\/[1-12]\/[0-31]\/[0-99]/11\/14\/46/g" txt.file
But it doesn't work and I'm not sure how to proceed
The suggested answers below haven't worked for me. I'm going to give some example data and see if this helps to clarify.
Popeye Sailor:156-454-3322:945 Bluto Street, Anywhere, USA 29358:3/19/35:22350
Let's pretend I'm trying to change Popeye's birth date (which is at the end), but I want to search without having to know his current one. I know using a regular expression is key here, but so far the examples I've seen haven't worked. Maybe providing the above example data will help
[Expected Output]
Popeye Sailor:156-454-3322:945 Bluto Street, Anywhere, USA 29358:11/14/46:22350
All I'm interested in changing is the birth date at the end to 11/14/46
[1-12]\/[0-31]
and[0-99]
do not mean 1 to 12, 0 to 31 and 0 to 99.[1-12]
means a range of characters starting from 1 till 1, and a 2. In essence:[12]
. (Compare with[0-1a]
.)[0-31]
means a range of characters starting from 0 till 3, and a 1:[0123]
.Similarly for
[0-99]
. Expressing a range of numbers with regular expressions isn't easy.If the numbers don't use double digits (
01/06/33
), you'll have to do something like:[0-9]{1,2}
for day and month, and[0-9]{2}
for the year, or the regex will quickly grow unwieldy. This, of course, risks the selection of something like99/99/99
.For an example:
I assume you want to retain the name, so I used backreferences to refer to it in the substitution (the
\1
).Dates are tricky, but simplifying to a similar extent to your attempt…
Explanation
-r
for extended regular expressions. This allows (for example)?
.'
rather than double"
, so there's no shell expansion./
assed
delimiters, you can use whatever you want. Here I've used,
, so that we don't need to escape literal/
s.1?[0-9]
match an optional1
and required 0-9, for the month.[1-3]?[0-9]
match and optional 1-3, and a required 0-9 for the day.[0-9]{2}
match two digits for the year.0/0/00
and19/39/99
will match, but you can tweak the regex more if you like. See the link above for more information.More comments
Note that this matches something like
PersonsName11/11/11
, and replaces the whole thing, similar to what your attempt tried to do. If you want to only replace the date, you can use the following instead.Here, we capture
PersonsName
, using parens. Then we can refer to it again in the replace section with\1
.You could use the below sed command,
It changes the date only on the lines which starts with
Popeye Sailor: