Search code examples
bashcommand-linemarkdownfilenames

Swap first and last four characters in a filename


StackOverflow.

I have a colleciton of notes from work. I keep them as markdown files, and had been formatting them with the date and year - for example, today's is titled 06132017.md

I am coming up on a year at work, so I have quite a few of these files. I wish to change the naming convention from month/day first to year first, so that I can sort them alphabetically and easily find dates I need.

So 06132017.md would become 20170613.md - this would keep 2016 and 2017 from mixing in aplha order. Is there a command I can run on a folder to do this?


Solution

  • If you have the Perl rename utility, it's rather simple to do:

    $ prename 's/^(....)(....)(\.md)$/$2$1$3/' *.md 
    06132017.md renamed as 20170613.md
    

    The dots match any character, the parenthesis group, and $N on the replacement side inserts the characters captured in the groups.

    Or just in Bash:

    $ for x in ????????.md ; do mv -v "$x" "${x:4:4}${x:0:4}.md" ; done
    '06132017.md' -> '20170613.md'
    

    ${var:n:m} takes a substring of length m, starting at position n from variable var.