Skip to content
Advertisement

linux command rename dates (YYYY.MMDD) to numbers(001,002,…,066,067) sequentially

I have renamed many files by using ‘rename‘.

However, I find a problem with conversion dates to numbers.

The file name is 2021.0801, 2021.0802, .. etc. (Year.Month&date)

I need to change Month&date parts to numbers of 001, 002, etc.

So I need to rename

JavaScript

to

JavaScript

I saw I can do it when I use rename or #, ? but I could not see the specific way to solve this.

Could you please let me know the way to rename these?

p.s. I tried num=001; for i in {0801..0930}; do rename $i $num *; (($num++)); done but it showed

JavaScript

Additionally, ls 2021.* shows only the files that I want to change.

Advertisement

Answer

Your script contains a few errors. I suggest to use https://www.shellcheck.net/ to check your scripts.

After fixing the errors, the (unfinished) result is

JavaScript

This has 3 remaining problems.

  1. The range {0801..0930} includes the numbers 0831, 0832, … 0899, 0900. This can be fixed by using two ranges {0801..0831} {0901..0930}
  2. The increment operation ((num++)) does not preserve the leading zeros. This can be fixed by conditionally adding 1 or 2 zeros.
  3. You call rename for every combination which will check all files and probably rename only one. As you know the exact file names you can replace this with a mv command.

The final version is

JavaScript

The script handles leading zeros for values of 1, 2 or 3 digits which is not needed here as all numbers are less than 100. For this case, it can be simplified as

JavaScript

The script will execute these commands:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement