How to Use sed to Rename Multiple Files


Often you may want to use sed to rename multiple files at once.

You can use the following basic syntax to do so:

for i in *; do
  mv "$i" "`echo $i | sed "s/team/team_info/"`";
done

This particular example renames each file in the current directory that contains the pattern team with the new pattern team_info.

Note that we use the sed s command to substitute one pattern with another specific pattern.

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

Example: How to Use sed to Rename Multiple Files

First, we can use the ls command to list all folders and files in the current directory:

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

  • coaches.txt
  • managers.txt
  • team1.txt
  • team2.txt

Suppose that we would like to rename each file that contains team in the file name with team_info instead.

We can use the following syntax to do so:

for i in *; do
  mv "$i" "`echo $i | sed "s/team/team_info/"`";
done

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

sed rename multiple files

Notice that the team1.txt and team2.txt files have been renamed to team_info1.txt and team_info2.txt, respectively.

The two files that did not contain team in the file name simply kept the same file names.

Related Tutorials

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

How to Use sed to Insert a Line After Match
How to Use sed to Insert Line at Specific Line Number
How to Use sed to Delete Specific Line Numbers from File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply