Search code examples
pythonregexfindappendline

Python - Append line under another line that contains a certain string


I want to append the string "$basetexturetransform" "center .5 .5 scale 4 4 rotate 0 translate 0 0" (including the quotation marks) as a new line under every line that contains the string $basetexture.

So that, for example, the file

"LightmappedGeneric"
{
    "$basetexture" "Concrete/concrete_modular_floor001a"
    "$surfaceprop" "concrete"
    "%keywords" "portal"
}

turns into

"LightmappedGeneric"
{
    "$basetexture" "Concrete/concrete_modular_floor001a"
    "$basetexturetransform" "center .5 .5 scale 4 4 rotate 0 translate 0 0"
    "$surfaceprop" "concrete"
    "%keywords" "portal"
}

and I want to do it for every file that has the file extension ".vmt" in a folder (including sub folders).

Is there an easy way to do this in Python? I have like 400 .vmt files in a folder that I need to modify and it would be a real pain to have to do it manually.


Solution

  • This expression might likely do that with re.sub:

    import re
    
    regex = r"(\"\$basetexture\".*)"
    
    test_str = """
    "LightmappedGeneric"
    {
        "$basetexture" "Concrete/concrete_modular_floor001a"
        "$surfaceprop" "concrete"
        "%keywords" "portal"
    }
    "LightmappedGeneric"
    {
        "$nobasetexture" "Concrete/concrete_modular_floor001a"
        "$surfaceprop" "concrete"
        "%keywords" "portal"
    }
    
    """
    
    subst = "\\1\\n\\t\"$basetexturetransform\" \"center .5 .5 scale 4 4 rotate 0 translate 0 0\""
    
    print(re.sub(regex, subst, test_str, 0, re.MULTILINE))
    

    Output

    "LightmappedGeneric"
    {
        "$basetexture" "Concrete/concrete_modular_floor001a"
        "$basetexturetransform" "center .5 .5 scale 4 4 rotate 0 translate 0 0"
        "$surfaceprop" "concrete"
        "%keywords" "portal"
    }
    "LightmappedGeneric"
    {
        "$nobasetexture" "Concrete/concrete_modular_floor001a"
        "$surfaceprop" "concrete"
        "%keywords" "portal"
    }
    

    If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


    Reference

    Find all files in a directory with extension .txt in Python