Need clarification about a sed syntax

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
RobertX
Level 4
Level 4
Posts: 259
Joined: Thu Apr 12, 2012 6:09 pm

Need clarification about a sed syntax

Post by RobertX »

My question is concerned with the following command:

Code: Select all

date | cut -c5-11,25- | sed 's/\([0-9]\{1,2\}\)/\1,/'
The output is the following:

Code: Select all

May 8, 2012
I tried altering the sed syntax to something like the following, where the max string, which used to be 1, 2 is changed to 1, 4 like so:

Code: Select all

date | cut -c5-11,25- | sed 's/\([0-9]\{1,4\}\)/\1,/'
and it still outputs the following:

Code: Select all

May 8, 2012
I thought maybe if the computer would see that there are four number strings as max instead of two, it would take 2012 into consideration, and would probably output this:

Code: Select all

May 8, 2012,
What is the error of my thinking?
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
User avatar
xenopeek
Level 25
Level 25
Posts: 29597
Joined: Wed Jul 06, 2011 3:58 am

Re: Need clarification about a sed syntax

Post by xenopeek »

You know that you can specify the output format of date :)

Code: Select all

date +'%B %-d, %Y,'
Nicely prints:

Code: Select all

May 9, 2012,
Run "man date" from the terminal for other format options.

Or to do it with sed, include the g modifier at the end to indicate you want to do the substitution globally (repeatedly, instead of just the first occurrence).

Code: Select all

date | cut -c5-11,25- | sed 's/\([0-9]\{1,4\}\)/\1,/g'
I like the solution without sed better though :mrgreen:
Image
RobertX
Level 4
Level 4
Posts: 259
Joined: Thu Apr 12, 2012 6:09 pm

Re: Need clarification about a sed syntax

Post by RobertX »

xenopeek wrote:You know that you can specify the output format of date :)
Or to do it with sed, include the g modifier at the end to indicate you want to do the substitution globally (repeatedly, instead of just the first occurrence).

Code: Select all

date | cut -c5-11,25- | sed 's/\([0-9]\{1,4\}\)/\1,/g'
That's right! How did I forget about that?!?
User avatar
xenopeek
Level 25
Level 25
Posts: 29597
Joined: Wed Jul 06, 2011 3:58 am

Re: Need clarification about a sed syntax

Post by xenopeek »

Ah well, it is often the smallest things that you overlook as you stare at something not working :wink:
Image
Locked

Return to “Scripts & Bash”