How can I prepend filenames with ascending numbers like 1_ 2_?

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


If there are more than 9 files, I would use printf to pad the number to get the expected sort order, like this

n=0
for f in *
    do printf -v new "%2d$((++n))_$f"
    echo mv -v -- "$f" "$new"
done

Remove echo when you see the correct result.

Explanation

In this line, do printf -v new "%2d$((++n))_$f" we create a format for the new filenames and put it into the variable new.

%2d is a 2 digit decimal number. Instead of 2d, you can use 3d etc to get another leading 0 (if you have more than 99 files).

((++n)) increments the variable n (which we set to 0 at the start of the script). Since it is iterated once each time the loop is run, files get incremented name prefixes.

-v makes mv print what will be changed.

-- in the mv statement is to prevent filenames that start with - being interpreted as options.


  1. Open your directory in Nautilus.

  2. Highlight all of the files.

  3. Right-click, and select "Rename..." from the context menu.

  4. On the Rename dialog, click the +Add button.

  5. Select "1,2,3,4" under "Automatic Numbers"

  6. Then, in the Rename dialog, in the text entry field, insert an underscore "_" character between "[1, 2, 3]" and "[Original file name]".

    It should look like "[1, 2, 3]_[Original file name]"

  7. Click the Rename button.

Select "1,2,3,4" in the Rename dialog

The renamed files