Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am trying to replace the whitespaces in the output of date with '_' with no success.

$date
Fri Sep 14 14:10:04 EDT 2012

$ date | sed 's/ /_/'
Fri_Sep 14 14:10:24 EDT 2012

As you can see, the last command only replaced the first whitespace by a _'. Why did it skip the other whitespaces?

share|improve this question
7  
Most versions of date let you specify the format directly instead so you DON'T have to massage it later with other tools. –  jw013 Sep 14 '12 at 18:14

2 Answers 2

up vote 6 down vote accepted

Try:

$ date | tr ' ' '_'

or

$ date | sed 's/ /_/g'

Your command only replaced the first matching instance from the date input because that is the default behaviour of sed. By adding the g (global replacement) option to the end of the command, sed will instead match and replace all occurrences of the expression.

share|improve this answer
1  
In a case like this, tr is faster than a regexp substitution. –  JRFerguson Sep 14 '12 at 19:36

Just my 2 cents. If you want a date as a single word, a good format is the ISO 8601 standard 2012-09-14T21:08:12. It is terse, unambiguous, and its chronological order is the same as its alphabetical order.

date +%Y-%m-%dT%T

which on some systems you may even write as

date +%FT%T
share|improve this answer
    
This should probably be a comment. –  jw013 Sep 14 '12 at 20:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.