1

I need to send a date (formatted like 2011-06-07T05:34:28+0200) in a POST HTTP Request. In order for this to work, I need to change the '+' or '-' of the timezone by '%2B' or '%2D' respectively. What is the most efficient way to do this in a bash / sed one liner?

The following only change the '+' as there is a single '+' (the one in the timezone).

d1=$(date +%Y-%m-%dT%H:%M:%S%z) // -> 2011-06-07T05:34:28+0200
d2=$(echo $d1 | sed -e 's/+/%2B/')

How to change the '+' or '-' character only within the timezone in a single command?

Ωmega
  • 42,614
  • 34
  • 134
  • 203
Luc
  • 16,604
  • 34
  • 121
  • 183
  • What's wrong with `d1=$(date +%Y-%m-%dT%H:%M:%S%z | sed -e 's/+/%2B/')`? – Konerak Jun 08 '11 at 07:24
  • @konerak, it only take the '+'. If it happens to be a '-' in the timezone, it will not be taken into account. – Luc Jun 08 '11 at 12:09
  • Ugh. And `d1=$(date +%Y-%m-%dT%H:%M:%S%z | sed -e 's/+/%2B/' | sed -e 's/-/%2D/')` then? :) – Konerak Jun 08 '11 at 12:10
  • @mirod, in fact leaving the '+' in the timezone won't work. Strangely I do not have problems with the '-' in the date. – Luc Jun 08 '11 at 12:10
  • @Luc that's because + is a reserved character in URIs, but not - (see http://en.wikipedia.org/wiki/Percent-encoding) – mirod Jun 08 '11 at 12:30
  • @mirod, ok, thanks (I though '-' was also a reserved char in fact). ok, so my basic sed -e 's/+/%2B/' will do the trick ;) Cheers. – Luc Jun 09 '11 at 16:41
  • See this question: [URLEncode from a bash script](http://stackoverflow.com/questions/296536/urlencode-from-a-bash-script) – Francisco R Jun 08 '11 at 08:59

2 Answers2

1

In Perl you could try this:

perl -M'POSIX strftime' -l -e'%rep=( "+" => "%2B", "-" => "%2D"); $d= strftime( "%Y-%m-%dT%H:%M:%S%z", localtime()); $d=~s{([+-])}{$rep{$1}}g; print $d'

basically capture '+' or '-' and replace them by the appropriate escaped value.

but then thinking further about it, there should be a module to escape the URL for you. And indeed, that's what URI::Escape does, so there you go:

perl -M'POSIX strftime' -MURI::Escape  -l -e'$d= strftime( "%Y%%2D%m-%dT%H:%M:%S%z", localtime()); print uri_escape $d'

I can't believe there is nothing to shorten the awful "%Y%%2D%m-%dT%H:%M:%S%z" strftime format though.

update: so after taking glenn jackman's comment and getting rid of the extra variable, the final one-liner would be:

perl -M'POSIX strftime' -MURI::Escape -E'say uri_escape strftime "%FT%T%z", localtime'
mirod
  • 15,923
  • 3
  • 45
  • 65
0
d1=$(date +%Y-%m-%dT%H:%M:%S%z)
d2=$(echo $d1 | sed -e 's/+([0-1][0-9]00)/%2B\1/' | sed -e 's/-([0-1][0-9]00)/%2D\1/')
Ωmega
  • 42,614
  • 34
  • 134
  • 203