J.Carter J.Carter - 1 year ago 71
Linux Question

Generating systematic incremental numbered filenames in Bash

I have a random number of files with names as:


Note that the number of
files varies in different directories. For example, a directory may contain only one
(at least) or may contain any number of files with any higher number of digits.

To convert the random number of filenames in systematic incremental number, I used following script in a batch script:

setlocal enabledelayedexpansion
set /a count=1
for /f "tokens=*" %%a in ('dir /b /od *.txt') do (
echo ren "%%a" "id_!count!.txt"
set /a count+=1

The output for the above input would be:

ren "id_1000.txt" "id_1.txt"
ren "id_2000.txt" "id_2.txt"
ren "id_3000.txt" "id_3.txt"
ren "id_4000.txt" "id_4.txt"

It first detects the number of
files are there in the current directory, and then changes to the higher number with normal count order: 1, 2, 3, 4, etc. and echo a line.

Although I tried to search for alternative commands for Ubuntu, I could not find any satisfactory result.

I am very new to the Linux shell, any help in this matter will be appreciated.


Answer Source
shopt -s globstar
for a in **/*.txt; do 
        mv "$a" id_$n.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download