Bash: How to Add Prefix to All Files in Directory


Often you may want to use Bash to add a prefix to all files with a specific extension in a directory.

You can use the following syntax to do so:

for file in *.txt; do mv "$file" "new_${file}"; done 

This particular example will add the prefix new_ to the beginning of each .txt file in the current directory.

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

Example: Add Prefix to All Files in Directory in Bash

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

We can see that the current directory contains the following files:

  • coaches.txt
  • employees.csv
  • interns.csv
  • owners.txt
  • players.txt

Suppose that we would like to add the prefix new_ to the beginning of each .txt file in this directory.

We can use the following syntax to do so:

for file in *.txt; do mv "$file" "new_${file}"; done

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

Bash add prefix to filename

Notice that when we use the ls command again to view the updated files in the current directory, we can see that each .txt file has had the prefix new_ appended to it:

  • coaches.txt has been renamed to new_coaches.txt
  • owners.txt has been renamed to new_owners.txt
  • players.txt has been renamed to new_players.txt

All other files in the current directory that did not have a .txt extension have been left unchanged.

Related Tutorials

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

Bash: How to Remove Prefix from All Filenames
Bash: How to Remove Prefix from a String
Bash: How to Add Suffix to All Files in Directory
Bash: How to Remove Prefix from a String

Leave a Reply