user2355173
user2355173

Reputation: 1

change string in variable in bash

When I assign in a bash script

DATE=`date`

and

TODAY=${DATE:4:7}

then TODAY contains "Jul 2 " instead of "Jul{2 spaces} ".

So I want to change the first space in $TODAY into two spaces.
How do I do that?
Or how can I avoid the first wrong assignment to $TODAY?

Upvotes: 0

Views: 138

Answers (4)

Ian Kenney
Ian Kenney

Reputation: 6426

use the date params to format the date how you want

date "+%b %_d"

will pad the day with space giving the 2 spaces you are after

Upvotes: 1

devnull
devnull

Reputation: 123448

  1. Quoting is the key.
  2. Use $(...) instead of backticks.

You'll find that spaces are preserved:

$ DATE="$(date)"
$ echo "${DATE}"
$ Tue Jul  2 11:43:21 GMT 2013
$ TODAY=${DATE:4:7}
$ echo "*${TODAY}*"
$ *Jul  2 *

Upvotes: 1

DRC
DRC

Reputation: 5048

if you want current month followed by two spaces:

date +'%b  '

or, for the long name:

date +'%B  '

to assign the command to a variable just use $() operator like this:

DATE=$(date +'%b  ')

and print it like this

echo "$DATE is the current month, with more spaces\!"

Upvotes: 1

fedorqui
fedorqui

Reputation: 289495

If you just want Jul 2, why not using date options?

$ date "+%b %-d"
Jul 2

Upvotes: 2

Related Questions