Linux – How to rename multiple files in a directory in some pattern in Linux

linuxlsshell

I have a directory which has files with random names. What I want to do is rename the files with file1, file2 and so on.The lexicographically smaller file name should be numbered with smaller number. How can I do that?

Best Answer

A simple bash script should do it.

#!/usr/bin/env bash

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

To help with a line-by-line explanation:

  1. Location of the bash shell this is executing under, determined by your environmental variable.
  2. Set the variable "count" to 0
  3. Creates a for-loop, iterating over the output of the command ls (sorted alphabetically by default).
  4. Moves (i.e. renames) the file "i" (current one in the loop) to file#.ext. The "#" is the current number in "count" and the stuff past the "." is a quick way to get the current file extension (so this could work in a folder of various file extensions).
  5. Increment the counter variable

loop, loop, loop

  1. done!

Note:

  1. This executes in whatever directory you are executing it from. So as a script, you'd want to add a command line argument. Instead I would open a terminal, navigate to the directory to do this on, and execute the following (exactly):

    for i in *; do mv "${i}" "file${count}".`echo "${i}" | 
      awk -F. '{print $2}'`; ((++count)); done
    
  2. This is assuming that you only have file names such as "file.txt" not "this.is.a.file.txt"

Related Question