Ubuntu: Rename files incrementally in a specific directory?



Question:

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 ?


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%d.txt", ++$ENV{c})/e' *  

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

c=0 rename -n 's/.*/sprintf("file%d.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.


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   

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »