[PLUG] Sed syntax error

Robert Citek robert.citek at gmail.com
Tue Nov 15 18:53:54 UTC 2016


On Tue, Nov 15, 2016 at 10:50 AM, Robert Citek <robert.citek at gmail.com> wrote:
> On Tue, Nov 15, 2016 at 10:30 AM, Rich Shepard <rshepard at appl-ecosys.com> wrote:
>>    Trying to change the date format from a forward slash (/) to a dash (-).
>> There's a syntax error in my sed script: "file change-date-format.sed line
>> 6: invalid reference \3 on `s' command's RHS" and I'm not seeing why. Here's
>> the script:
>>
>> #!/usr/bin/sed
>> #
>> # Change date format from / to -.
>>
>> s/[0-9]\{4\}\/[0-9]\{2\}\/[0-9]\{2\}/\1-\2-\3/g
>>
>>    Please show me what I've done incorrectly here.
>
> Example input and sample expected data would be helpful.  But if I
> were to guess (which is usually a really bad idea), your input date
> string looks like this:
>
> 1996/03/10
>
> and you want your output data to look like this:
>
> 1996-03-10
>
> If that's correct (highly unlikely because I am guessing), then this would work:
>
> $ <<< '1996/03/10' tr / -
> 1996-03-10
>
> But if you insist on sed:
>
> $ <<< '1996/03/10' sed -e 's#/#-#g'
> 1996-03-10
>
> Or insist on sed using groups:
>
> $ <<< '1996/03/10' sed -e
> 's#\([0-9]\{4\}\)\/\([0-9]\{2\}\)\/\([0-9]\{2\}\)#\1-\2-\3#g'
> 1996-03-10
>
> or
>
> $ <<< '1996/03/10' sed -re
> 's#([0-9]\{4\})\/([0-9]\{2\})\/([0-9]\{2\})#\1-\2-\3#g'
> 1996/03/10

Oops!  Corrected:

$ <<< '1996/03/10' sed -re 's#([0-9]{4})/([0-9]{2})/([0-9]{2})#\1-\2-\3#g'
1996-03-10

This is why you want to KISS -- use tr, if possible.

Regards,
- Robert



More information about the PLUG mailing list