Ubuntu – How to prepend filenames with ascending numbers like 1_ 2_

bashbatch-renamecommand line

How can I add numbers to the files in one directory?

In one directory I have files like below:

fileA
fileB
fileC
fileD

I want to prepend ascending numbers to them, like this:

1_fileA
2_fileB
3_fileC
4_fileD

Thank you in advance.

Best Answer

One of the solutions:

cd <your dir> then run in bash (copy and paste in command-line):

n=1; for f in *; do mv "$f" "$((n++))_$f"; done

Bash script case:

#!/bin/bash
n=1
for f in *
do
  if [ "$f" = "rename.sh" ]
  then
    continue
  fi
  mv "$f" "$((n++))_$f"
done

save it as rename.sh to dir with files to rename, chmod +x rename.sh then run it ./rename.sh

Related Question