Need clarification about a sed syntax

Forum rules
Before you post please read how to get help
RobertX
Level 2
Level 2
Posts: 66
Joined: Thu Apr 12, 2012 6:09 pm

Need clarification about a sed syntax

Postby RobertX » Tue May 08, 2012 5:43 pm

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?

User avatar
xenopeek
Level 23
Level 23
Posts: 19685
Joined: Wed Jul 06, 2011 3:58 am
Location: The Netherlands

Re: Need clarification about a sed syntax

Postby xenopeek » Wed May 09, 2012 4:29 pm

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 2
Level 2
Posts: 66
Joined: Thu Apr 12, 2012 6:09 pm

Re: Need clarification about a sed syntax

Postby RobertX » Thu May 10, 2012 11:40 pm

Vincent Vermeulen 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 23
Level 23
Posts: 19685
Joined: Wed Jul 06, 2011 3:58 am
Location: The Netherlands

Re: Need clarification about a sed syntax

Postby xenopeek » Fri May 11, 2012 1:38 am

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


Return to “Scripts & Bash”

Who is online

Users browsing this forum: No registered users and 1 guest