Home > database >  Can you convert a date to yyyy/mm/dd using sed?
Can you convert a date to yyyy/mm/dd using sed?

Time:06-29

I have a utility that outputs the software expiration date into a text file called expiration. The file has one line and it is below:

node_software_expiration_date Sat Jul 6 23:59:59 2025

I'd like to replace the text in the file to read:

node_software_expiration_date 20250706

I'm using sed to replace the current text. I can't edit the utility. Open to other options.

I'm running this in cron:

./export_expiration && sed -e 's/Software Expiration/node_software_expiration_date /' > expiration

CodePudding user response:

You can use date --date=STRING to parse pretty much any free-form date string (it accepts many different syntaxes, so is pretty robust), and then FMT to output whatever format you have. The main difficultly with your example is replacing the file in place. Something like:

read prefix date < expiration
echo $prefix $(date --date="$date"  %Y%m%d) > expiration

should do the trick in a shell script. Note that if the input date string includes a time close to midnight in some other timezone, this may end up adjusting the day by one, which might actually be what you want.

CodePudding user response:

Using any awk in any shell on every Unix box:

$ awk '{printf "%s ddd\n", $1, $6, (index("JanFebMarAprMayJunJulAugSepOctNovDec",$3) 2)/3, $4}' file
node_software_expiration_date 20250706

CodePudding user response:

$ awk '{n=$1; $1=""; printf "%s ",n; print |"date -d \"" $0 "\"  %Y%m%d"} file
node_software_expiration_date 20250706
  • Related