This content originally appeared on Level Up Coding - Medium and was authored by Johnny Simpson
Renaming files is something that occurs frequently, and in Linux on terminal, there are many ways to rename files. Let’s look at some of the main ways you can rename your files on Linux and other Unix based systems like MacOS.
Linux Commands
If you’re brand new to Linux commands, read my full guide on Linux commands them here.
Renaming files with the mv Command
The mv command moves a file to another place. It can also be used to move a file to the same location, and simply change it's name. For example, if you wanted to rename a file called file-1.txt to file-2.txt, you would first cd into that directory, and run the following:
mv file-1.txt file-2.txt
This technically “moves” the file, but in reality the end result is that the file is renamed and in the same location.
Renaming multiple files
If you want to rename more than one file at once, we can’t just use the mv command. For that, we need to loop through each file we want to rename. We can use this in conjunction with the find command to find all the files that fit our criteria easily. For example, the below will find all .txt, .csv and .html files, and turn them into .js files:
for f in $(find . -name '*.txt' -or -name '*.csv' -or -name '*.html'); do
mv $f ${f%.*}.js
done
Let’s look at how this works in a little more detail:
- We run a for loop, for f in $(). This will find all files, where it matches what is inside $(). In this example, it finds anything with the file type .txt, .csv, or .html. You can learn more about find here.
- For each of the matching files, we run the mv command. We run mv $f ${f%.*}.js.
- $f is the current matching file we are looping through.
- ${f%.*}.html is saying rename any file with any extenstion ({f%.*} could be {f%.html}, {f%.csv}, etc), and change its name to the file name with our new extension, .js.
After that, you’ll have successfully moved all files.
How to Rename Files in Linux and MacOS Terminal was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Johnny Simpson
Johnny Simpson | Sciencx (2022-04-26T13:27:39+00:00) How to Rename Files in Linux and MacOS Terminal. Retrieved from https://www.scien.cx/2022/04/26/how-to-rename-files-in-linux-and-macos-terminal/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.