How To Add and Remove File Extensions To Multiple Files In Linux

Changing the file extension for multiple files in a Linux directory is easy. If you need to add something to the end of every filename in a directory or if you want to remove text from the end of a filename in a directory you can use a simple bash loop.

A bash loop will allow you to loop through all the selected files and perform a command (or commands) on all the files which match the selected files.

To add a ".old" file extension or ending to all the files in a directory you should run:

for file in *; do mv -- "$file" "$file.old"; done 

This selects all the files in the current directory (the *) and loops through them. While looping, it moves each selected file to the filename + .old. You can also select only certain files. For example, if you want to add a .gz extension to all txt files (and only .txt files) you would run:

for file in *.txt; do mv -- "$file" "$file.gz"; done 

Removing an extension or ending of a filename is similar. To remove a .old extension from all the files in the current directory, run:

for file in *.old; do mv -- "$file" "${file%%.old}"; done

What you are doing is running a bash loop. You can also write a bash script to do the above, or to add more complex functionality.