Home > database >  How do I remove digits from the middle of a numeric date using bash or applescript?
How do I remove digits from the middle of a numeric date using bash or applescript?

Time:01-26

I found a way to extract the creation date of a pdf and I would like to use it as part of the new filename. However, I want the date to be in the format "mmddyy" and it is returning at "mmddyyyy". How can I remove the first "yy" using either bash or applescript?

Here is the code that I am using to get the date to the 8 digit form:

mdls $f | grep kMDItemContentCreationDate | head -n1 | awk '{gsub("[^[:digit:]] "," ");print $2$3$1}'

Is there a way to modify this to only return the 6 digit date or do I need to do something to the 8 digit return?

I have tried assigning variables to different awk commands to extract pieces of the string but that isn't working.

CodePudding user response:

Since you already have an awk command that parses the date (printed in ISO format yyyy-mm-dd ... by mdls) it would make sense to adapt that command instead of adding another.

I don't have a mac, so I cannot try this. From what I found, it seems mdls prints something like this:

$ mdls -name kMDItemContentCreationDate file.pdf
kMDItemContentCreationDate = 2023-01-25 17:25:43 -0200

From that output, you extract the separate numbers (the first number$1 is the year, the second number $2 the month and so on) and change their order (print $2$3$1).

To remove the first two digits of the year ($1) you can take the substring starting at the 3rd digit of that number (substr($1,3), assuming that all years have exactly four digits) or take the remainder when dividing by 100 (the modulo operator % does this):

$ mdls -name kMDItemContentCreationDate file.pdf |
  awk '{gsub("[^0-9] "," "); print $2 $3 $10}'
012523

CodePudding user response:

Kudos to Socowi - adding the CLI option for creation date removed the need for grep and head, and is the better solution, but I wanted to point out that awk still eliminates the need for both in those cases where you don't have the better option of reducing and simplifying your input.

mdls "$f" | awk '/kMDItemContentCreationDate/{gsub("[^[:digit:]] "," ");print $2$3$1; exit}'
  • Related