Ubuntu – Rename multiple .txt files changing some characters in specific positions

bashbatch-renamecommand linefiles

I have a collections of hundreds of .txt files in the same folder in Ubuntu 16.04, and they're named with strings and index numbers, like that:

a01_s01_e01_skeleton.txt
a01_s01_e02_skeleton.txt
a01_s01_e03_skeleton.txt
a01_s02_e01_skeleton.txt
...
a20_s10_e02_skeleton.txt
...

I must remove the 0 (zeros) from every .txt file where the number is smaller than 10, so in the end I'll have:

instead of : a01_s01_e01_skeleton.txt 

it will be: a1_s1_e1_skeleton.txt #notice that the 0s are gone. 

EDIT

The position of the numbers is always the same, like in the examples. The files have a logic of order, so the renaming process must be totally correct.

How could I do that using the command line?

Best Answer

Ok, just for fun, no doubt there are shorter cli solutions, but in python, the script below does the job if the directory is "flat" (as you say) and all files in it are valid files to rename. If not, we need to add an exception, so here we go:

import shutil
import sys
import os

dr = sys.argv[1]

for f in os.listdir(dr):
    sections = f.split("_")
    newname = "_".join(
        [s[0] + str(int(s[1:])) for s in sections[:3]] + [sections[-1]]
    )
    shutil.move(os.path.join(dr, f), os.path.join(dr, newname))

To use:

  • Copy the code into an empty file, save it as rename_stuff.py
  • Run it with the directory as argument:

    python3 /path/to/rename_stuff.py </directory/with/files>
    

As always, first try on a sample directory.

Explanation

  • Read the files in the directory:

    for f in os.listdir(dr):
    
  • Split the name by "_":

    sections = f.split("_")
    
  • On the first three sections, replace the two (or more) -digit number by its int- ("real") value, so 01 -> 1, 10 -> 10, 020 -> 20, 000300 -> 300 and so on.

  • Subsequently, glue the sections together again:

    newname = "_".join(
        [s[0] + str(int(s[1:])) for s in sections[:3]] + [sections[-1]]
    )