I have a random number of files with names as:
id_1000.txt id_2000.txt id_3000.txt id_4000.txt
Note that the number of .txt
files varies in different directories. For example, a directory may contain only one id_1000.txt
(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 id_*.txt
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.
Thanks
Advertisement
Answer
shopt -s globstar n=0 for a in **/*.txt; do ((n++)) mv "$a" id_$n.txt done