Replace duplicate textures with exisiting one in Python
Try this
import bpy, re

def get_original_name(name):
    &quot;&quot;&quot;When name looks like 'X.001', return 'X'. Otherwise None.&quot;&quot;&quot;
    i = name.rfind('.')
    if i != -1:
        suf = name[i+1:]
        if len(suf) == 3 and suf.isdigit():
            return name[:i]
    return None

for material in bpy.data.materials:
    if material.node_tree is None:
        continue
    for node in material.node_tree.nodes:
        if node.type != 'TEX_IMAGE':
            continue
        if node.image is None:
            continue
        original_name = get_original_name(node.image.name)
        if original_name is None:
            continue
        if original_name in bpy.data.images:
            node.image = bpy.data.images[original_name]