Bash: How to Add Files Extension to All Files


Often you may want to use Bash to add a specific file extension to all files in a directory that do not have an extension.

You can use the following syntax to do so:

find . -type f  ! -name "*.*" -exec mv {} {}.txt \;

This particular example will add the file extension .txt to all files in the current directory that do not have an extension.

Here is what the various commands do:

  • find .: Match all items in current directory
  • -type f: Match only the files
  • ! -name “*.*”: Match only files that do not have an extension
  • -exec mv {} {}.txt \;: Rename each matched file with .txt at the end

Note that you can also replace find . with find /some/directory/path to match all files in a specific directory.

The following example shows how to use this syntax in practice.

Example: How to Add File Extension to All Files in Bash

Suppose that we would like to add the file extension .txt to all files in our current directory that have no extension.

We can use the ls command to first view all items in our current directory:

We can see that this directory contains the following items:

  • managers
  • owners
  • teams1.txt
  • teams2.txt
  • teams3.txt

Suppose that we would like to add .txt as the file extension to the two files that currently do not have an extension.

We can use the following syntax to do so:

find . -type f ! -name "*.*" -exec mv {} {}.txt \;

The following screenshot shows how to use this syntax in practice:

Bash add file extension to all files

Notice that when we use the ls command again to view the updated files in the directory we can see that the two files that had no extension now have .txt as the extension:

  • managers.txt
  • owners.txt

Feel free to replace .txt with any other file extension that you’d like to use.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Delete All Files Without an Extension
Bash: How to Delete All Files with Specific Extension
Bash: How to Check if File Has Specific File Extension

Leave a Reply