coolharsh55
coolharsh55

Reputation: 1199

bash rename files with prefix serial number

I have loads of files in a folder. I want to do two things:

  1. prefix them with xxx three digit serial numbers - ascending: 001 002 and so on
  2. remove the prefix from their names, so 001a.xyz = a.xyz

I intend to do this using a simple bash script. What's the most elegant and simple to understand way to do this?

edit

the files are on a removable device, and I cannot seem to set chmod +X on the script on the device. So how do I run a script from my home directory which will change the files in another directory?

Upvotes: 1

Views: 2194

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295373

To add prefixes:

counter=1
for f in *; do
  printf -v prefix_str '%03d' "$((counter++))"
  mv "$f" "${prefix_str}$f"
done

To remove prefixes (caution -- this may overwrite if you have two files with the same suffix but different prefixes):

for f in [0-9][0-9][0-9]*; do
  mv "$f" "${f:3}"
done

Use mv -n to avoid overwriting when two files have the same suffix.

Upvotes: 4

jaypal singh
jaypal singh

Reputation: 77095

This should work:

#!/bin/bash

count=1
for file in *; do
  if [[ $file =~ [0-9][0-9][0-9].* ]]; then
    sfile="${file:3}"
    new=$(printf "%03d" ${count}) 
    mv "$file" "${new}${sfile}"
    ((count++))
  else
    new=$(printf "%03d" ${count})
    mv "$file" "${new}${file}"
    ((count++))
  fi
done

What this script does is, checks for a given file in the current directory. If the file has a prefix already it will remove it and assign a new sequential prefix. If the file has no prefix it will add a sequential prefix to it.

The end result should be, all the files in your current directory (some with and some without prefixes) will have a new sequential prefixes.

Upvotes: 1

Related Questions