loading...
Cover image for Bash: Rename specific files in a folder

Bash: Rename specific files in a folder

miku86 profile image miku86 Updated on ・1 min read

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

Further Reading

Questions

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

Posted on by:

miku86 profile

miku86

@miku86

Mentor & Educator & Senior Web Developer - I help people to reach their (career) goals. => https://miku86.com/mentoring

Discussion

markdown guide
 

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.

 

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
 

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.

Awesome, congrats!

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

 
 

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.