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 i开发者_运维百科s 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?
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'
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/')
精彩评论