Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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 ?

share|improve this question
    
do you mind if it is a python script? –  Stormvirux Mar 8 at 15:18
    
the script should be executed in terminal , but you can write your script . –  nux Mar 8 at 15:19
2  
for i in *.txt; do echo mv "$i" "file${i#file}"; done –  d0lph1n Mar 8 at 15:23

3 Answers 3

up vote 10 down vote accepted

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.
share|improve this answer
1  
can you explain your command ? –  nux Mar 8 at 15:24
    
@nux see the edits and feel free to discuss if necessary. –  souravc Mar 8 at 15:29
    
ok thank you ,i will consider it as a right answer , i found a small script that satisfy my needs too . –  nux Mar 8 at 15:34
    
+1 for your simple answer –  nux Mar 8 at 15:35

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.

share|improve this answer
    
@souravc oh shoot, you're right, thanks! –  janos Mar 8 at 16:49

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|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.