Rename files incrementally in a specific directory?

10,480

Solution 1

You can use this in terminal to rename files as you wished,

j=1;for i in *.txt; do mv "$i" file"$j".txt; let j=j+1;done

It will do the job.

Explanation:

  • Set a counter j, initially set it to 1
  • Initiate a for loop and use a shell glob *.txt to obtain all txt files.
  • for each file rename it using mv and increase the counter by 1.

Solution 2

You can use the rename command, which is usually included in a default installation:

c=0 rename 's/.*/sprintf("file%05d.txt", ++$ENV{c})/e' *

Use the -n flag if you want to do a test first:

c=0 rename -n 's/.*/sprintf("file%05d.txt", ++$ENV{c})/e' *

The way this works is, for each argument, it executes the perl s/// expression, and performs the rename from the original to the replaced string. In the replacement string I use sprintf to format the name, where I use the environment variable c as the counter from 1.

In most cases you also may need leading "0" for each number, %05d does the trick, where 5 is number of digits.

Solution 3

The following command will also rename files incrementally :

cd (directory containing files )

Then run this script :

count=1
for i in *; do
    mv "${i}" file${count}.`echo "${i}" | awk -F. '{print $2}'`
    ((++count))

done 
Share:
10,480

Related videos on Youtube

nux
Author by

nux

The Quieter you are , the more you are able to hear . "Once you stop learning, you start dying". -Albert Einstein Started learning Python . I am from Lebanon .

Updated on September 18, 2022

Comments

  • nux
    nux over 1 year

    I have a directory containing bunch of .txt files , I need a command to rename these files by one command , so their name will be : file1.txt , file2.txt, file3.txt , etc .

    Any Help ?

    • Stormvirux
      Stormvirux about 10 years
      do you mind if it is a python script?
    • nux
      nux about 10 years
      the script should be executed in terminal , but you can write your script .
    • Fakhri Zulkifli
      Fakhri Zulkifli about 10 years
      for i in *.txt; do echo mv "$i" "file${i#file}"; done
  • nux
    nux about 10 years
    can you explain your command ?
  • sourav c.
    sourav c. about 10 years
    @nux see the edits and feel free to discuss if necessary.
  • nux
    nux about 10 years
    ok thank you ,i will consider it as a right answer , i found a small script that satisfy my needs too .
  • Kostanos
    Kostanos about 5 years
    Great example, should be a top answer. With %05d instead of %d you can add leading 0 to the name, with 5 digits.