I have a folder of markdown files - I need to batch rename THE FILES. I need to prepend a date, and the date is inside the file in this format:

Title: Title-of-blog-article
Date: 2012-03-07

I have managed to find a way to grab the date using awk. I can not seem to find the right magic to then take that date from awk and rename the file with it. Intended naming scheme:



There are 150+ files in this folder. I've tried bash for loops and tested it with mv and echo. So far in the loop the awk variable never changes, just uses the field from the very first file. So I definitely need help.

  • 1
    "There are 150+ files in this folder".... so you want rename a single directory 150+ times for each file found? you can just rename it directly once. if you mean rename files then please edit your question to make it clear.. – αғsнιη Jun 13 '18 at 5:19

Probably not very efficient, but how about

for f in *; do 
  d=$(awk '/^Date:/ {print $2; exit}' "$f")
  [[ -n "$d" ]] && echo mv --no-clobber -- "$f" "${d}-${f}"

Remove the echo once you are satisfied that it is doing the right thing.

  • LIFESAVER! OK, that's probably a bit overly melodramatic. But seriously, I had been dancing all around that one! I was trying *.md, I wasn't sure where to put the $f, I didn't have the stuf in [[ ]] at all, didn't know about the --no-clobber option, and was making all kinds of wrong guesses about the syntax to get the variables into the new file name. This worked perfectly! Also, I didn't know the for loop could be entered in pieces, which was required to make it work, one line at a time... – dixonge Jun 13 '18 at 0:06
  • @donblanco glad it worked for you - the --no-clobber is really just a safety measure (in case renaming conflicts with an existing file); the [[ -n "$d" ]] skips any cases for which the awk command returns an empty string - again arguably not necessary but good practice – steeldriver Jun 13 '18 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.