linux怎么读写ini文件

avatar
作者
筋斗云
阅读量:1

要读写INI文件,你可以使用Shell脚本或编程语言来实现。下面是使用Shell脚本和Python编程语言来读写INI文件的示例。

Shell脚本示例:

#!/bin/bash  # 读取INI文件 read_ini_file() {     local ini_file=$1     local section=$2     local option=$3     local value      value=$(awk -F '=' "/\[$section\]/, /^\[.*\]/ { if (\$1 == \"$option\") print \$2 }" $ini_file)     echo $value }  # 写入INI文件 write_ini_file() {     local ini_file=$1     local section=$2     local option=$3     local value=$4      if ! grep -q "\[$section\]" $ini_file; then         echo "[$section]" >> $ini_file     fi      if ! grep -q "^$option=" $ini_file; then         echo "$option=$value" >> $ini_file     else         sed -i "s/^$option=.*/$option=$value/" $ini_file     fi }  # 调用示例 ini_file="config.ini" section="database" option="host"  read_value=$(read_ini_file $ini_file $section $option) echo "读取到的值:$read_value"  new_value="localhost" write_ini_file $ini_file $section $option $new_value 

Python示例:

import configparser  # 读取INI文件 def read_ini_file(ini_file, section, option):     config = configparser.ConfigParser()     config.read(ini_file)     value = config.get(section, option)     return value  # 写入INI文件 def write_ini_file(ini_file, section, option, value):     config = configparser.ConfigParser()     config.read(ini_file)     config.set(section, option, value)     with open(ini_file, 'w') as configfile:         config.write(configfile)  # 调用示例 ini_file = 'config.ini' section = 'database' option = 'host'  read_value = read_ini_file(ini_file, section, option) print(f"读取到的值:{read_value}")  new_value = 'localhost' write_ini_file(ini_file, section, option, new_value) 

以上是使用Shell脚本和Python编程语言读写INI文件的示例,你可以根据自己的需求进行修改和扩展。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!