Harness the Combinatoric Power of Command-Line Tools and Utilities

../Tips

Rename Multiple Files

commands files

Published May 14, 2024

You can rename a file using the mv command:

mv file.txt newname.txt

If you need to mass-rename files, you can do so with a for loop in Bash.

For example, to rename all files in the current directory with the .txt extension to have the .md extension instead, execute the following command:

for file in ./*.txt; do mv -v "${file}" "${file%.*}.md"; done

Within the mv command, you use some variables and shell substitution:

  • ${file} is the variable that refers to the current file name. The file variable is declared in the for loop.
  • % indicates that you want to remove a suffix pattern from the end of the variable’s value.
  • .* is the pattern that matches the dot (.) followed by any characters (*), which represents the file extension in this case.
  • ${file%.*} removes the .txt extension from the file name.
  • "${file%.*}.md" removes the .txt extension and appends .md, creating the resulting file name.

Using the mv command with the -v flag gives you a detailed output.

Running the command gives the following output:

renamed './chapter1.txt' -> './chapter1.md'
renamed './chapter2.txt' -> './chapter2.md'
renamed './chapter3.txt' -> './chapter3.md'
renamed './chapter4.txt' -> './chapter4.md'