I want to convert a String in %m%d%Y format to date.
But, getting invalid date error as shown below:
bash-4.1$ date -d '10042015' +"%m%d%Y"
date: invalid date `10042015'
How to fix it?
The date + option sets only the output format, not the input. You'll need to use a different tool or format the string first:
date --date="$(sed 's/^\([0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9][0-9][0-9]\)$/\3-\1-\2/' <<< '10042015')"
or
date --date="$(sed 's/\(..\)\(..\)\(....\)/\3-\1-\2/' <<< '10042015')"
or simply
date --date="$(sed 's/\(.*\)\(....\)$/\2\1/' <<< '10042015')"
(thanks @Costas). Even though the last two are shorter I would still suggest the first one, because:
%m%d%Y format so sed 's/\(.*\)\(....$\)/\2\1/' is enough
20151004or10/04/2015man bashand look for Substring Expansion