-2

we are modifying the expected format for some configuration files and I want to create a script to convert files of the old format to the new one. However, my scripting skills are rusty, I have to script so rarely that I forget script tools by the time I need them again. I'm looking for recomendations on how to do the scripts. My most complicated change would be modifying ini files, which currently will have multuple lines that look like this:

device.name = xxx

I would like to change the name to a label, and then append something to the name to make it unique. Specifically in this case I would probably use the name of the folder the file was found in. So if the file is in folder YY I would change the above to:

device.label = xxx
device.name = xxx_YY

The ordering of the two don't matter. Multuple device.name values will exist in each file and all must be updated.

I'm wondering what tool would be best to address this. Is this something that is simply done in bash scripting, or should I look to python. If this is done in bash, which I'm leaning towards, could someone give me an idea which bash tool I should use. I think I could make sed or awk do this, but I haven't been able to figure out how just yet. I can work out the exact syntax if need to (though syntax is welcome!), but a pointer to a good tool for the job would be appreciated.

dsollen
  • 6,046
  • 6
  • 43
  • 84

2 Answers2

0

This has been asked similarly before....Duplicate

import configparser
filename = r'C:\directory\sub_directory\FILE.INI'
config = configparser.ConfigParser()
config.read(filename)
config['device.label'] = config['device.name']
modified_name = str(config['device.name']) + '_' + filename.split['\\'][2]
config['device.name'] = modified_name

with open(filename, 'w') as configfile:
    config.write(configfile)

will yield:

device.label = xxx
device.name = xxx_subdirectory

This will need to be modified if say, you have sections in your file.

Community
  • 1
  • 1
user3727843
  • 574
  • 1
  • 4
  • 13
0

This is exactly the type of job awk was invented to do and does best. It's hard to say without some more sample input, but something like this sounds like what you need:

awk -v dir="$(basename "$PWD")" '{lbl=$0; sub(/name/,"label",lbl); print lbl RS $0 "_" dir}' file
Ed Morton
  • 188,023
  • 17
  • 78
  • 185