This short article will have limited usage as it shows how to automatically add an extension to multiple files in the Linux terminal. This is something not everyone needs to know, but something you need to know if you need to know it.
Let me explain…
First, I wrote a snippet of terminal code to help out a forum user. I decided that it was valuable enough to share with the larger world. As it’s just a snippet, it can be a short article.
In this case, the user had recovered many images and the recovered file names did not have a .jpg extension. They were going to manually edit a thousand files to add the .jpg extension. That’s not something you need to do. You can automatically add an extension to multiple files in the Linux terminal.
So, how does this work…
Automatically Add An Extension To Multiple Files:
Open your terminal and navigate to the appropriate directory. You can usually use your GUI file manager to navigate to the directory and then open the directory from that window. Otherwise, just use the cd command to navigate to the right directory.
The syntax to add the extension to all those files in that directory would be:
1 | rename 's/$/.<extension>/' * |
What we’re doing is using the rename command to search for anything with zero to one character and the asterisk is all characters including spaces. You should have rename available by default. I first tried using an asterisk in both places, but the command was having none of it.
If you want to test this, open your terminal and try this:
1 2 3 4 | mkdir temp cd temp touch foo bar foobar barfoo bar1 foo1 foobar1 ls |
That should show you the newly created files.
Next, just run:
1 | rename 's/$/.jpg/' * |
Now confirm that you’ve made the changes:
1 | ls |
Your output should match this one:
1 2 | $ ls bar1.jpg barfoo.jpg bar.jpg foo1.jpg foobar1.jpg foobar.jpg foo.jpg |
See? You’ll have added .jpg to all the files in that directory. We could use something like the find command and make it recursive, but this is good enough.
Closure:
There you have it. You have a short article that will show you how to add an extension to multiple file types. I figured this was useful enough to be shared with the wider world, maybe saving someone a bit of time and showing others how easily you can process things in the Linux terminal.
Thanks for reading! If you want to help, or if the site has helped you, you can donate, register to help, write an article, or buy inexpensive hosting to start your site. If you scroll down, you can sign up for the newsletter, vote for the article, and comment.
Last Updated on February 10, 2024 by KGIII