linux怎么读写ini文件

   2025-02-15 3460
核心提示:要读写INI文件,你可以使用Shell脚本或编程语言来实现。下面是使用Shell脚本和Python编程语言来读写INI文件的示例。Shell脚本示

要读写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文件的示例,你可以根据自己的需求进行修改和扩展。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言