DEV Community

Cover image for Bash: Rename specific files in a folder
miku86
miku86

Posted on • Updated on

Bash: Rename specific files in a folder

Recently I've built a script to download all my articles from dev.to into markdown files.

I used the timestamp and the name of the article.

Alt Text

This is working, but there is one annoying thing: every post has a date in its file name and its frontmatter.

Alt Text

That leads to:

  • Increased complexity: Would have to change the date in both places if I would want to change the date.
  • What would be the source of truth in case of two different dates?

Problem

Alt Text

Desired Outcome

Alt Text

Let's tackle this problem

# loop over every file with `md` extension, assign it to `file`
for file in *.md 
do
  # rename (by variable expansion starting from position 11)
  mv "$file" "${file:11}" 
done
Enter fullscreen mode Exit fullscreen mode

Further Reading

Questions

  • Do you write bash scripts?
  • What's your favorite one?

Latest comments (6)

Collapse
 
vlasales profile image
Vlastimil Pospichal

Use command rename.

Collapse
 
miku86 profile image
miku86

Hey Vlastimil,

thanks for showing an alternative.

While solving my challenge,
I found out, that there are 2 packages called rename.

One that is working with perl and uses regex,
one that comes from util-linux, that doesn't use regex.

The user would have to install the perl one, depending on the distro (s)he's using.

Therefore I use the solution with the lowest complexity, e.g. installing additional packages after checking which rename its distro is using.

Collapse
 
rjmoise profile image
Ryan

I have been trying to write a quick bash script for work to simply add an extension to the end of all files in a folder (filename.OGext.NEWext) but have little experience and it hasn't been as easy as I thought it would be.

Collapse
 
miku86 profile image
miku86

Hey Ryan,

did you manage to achieve your goal?

I would try something like this:

# * wildcard for all files
for file in *
do
  # -v will show you what has been done.
  mv -v "$file" "$file.yourdesiredextension"  
done
Collapse
 
rjmoise profile image
Ryan

Seeing your post inspired me to tackle it once again and I had just got it working before your comment! I don't do bash scripting very often but it is something I am trying to commit to doing more often.
Thanks.

Thread Thread
 
miku86 profile image
miku86

Awesome, congrats!

Yeah, me too, I don't use it that much.