Home > database >  Remove a portion of a variable length string and store it in a new variable
Remove a portion of a variable length string and store it in a new variable

Time:10-14

I'm trying to remove the HH MM(minute) SS section in the following example:

data=`security find-certificate -c "ABC Company Root 2016 CA" -p | openssl x509 -text | grep "Not After"`

echo $data
Not After : Mar 6 01:00:53 2026 GMT
date1=`cut -c 13-32 <<< $data`
echo $date1
Mar 6 01:00:53 2026

The problem is that I cannot go by character position because the text length can change. Example, the date could be 16th instead of 6 (or any double digit). The date will be derived and will not be static. Therefore I need a way to look for characters immediately before and after the ":" and remove them.

I would like the output to be in the following format (MM DD YYYY):

Mar 6 2026

CodePudding user response:

A more robust solution than string parsing is to use date -d to read the date in and then <format> to spit it back out in the format of your choice. %b %-e %Y will give you Mar 6 2026, and you have the ability to change it to another format if you like. See date --help for a list of format specifiers.

$ date -d "$date1"  '%b %-e %Y'
Mar 6 2026

CodePudding user response:

With bash:

data='Not After : Mar 6 01:00:53 2026 GMT'
read x x x m d x y x <<< $data
echo "$m $d $y"

Output:

Mar 6 2026
  • Related