Linux INI文件是一种简单的文本文件格式,通常用于存储配置信息。INI文件由节(sections)、键(keys)和值(values)组成。节用方括号[]
括起来,键值对用等号=
连接。下面是一些基础概念和相关信息:
[]
括起来的部分,例如[section_name]
。key_name
。value
。[database]
host = localhost
port = 3306
user = admin
password = secret
[logging]
level = info
file = /var/log/app.log
读取 INI 文件
#!/bin/bash
config_file="example.ini"
section="database"
key="host"
value=$(grep -E "^$section[[:space:]]*\$" $config_file | grep -E "^$key[[:space:]]*=" | cut -d'=' -f2-)
echo "$key in $section is $value"
写入 INI 文件
#!/bin/bash
config_file="example.ini"
section="database"
key="host"
value="new_host"
# Check if section exists, if not add it
if ! grep -q "^$section[[:space:]]*\$" $config_file; then
echo "$section {" >> $config_file
echo " $key=$value" >> $config_file
echo "}" >> $config_file
else
# Update existing key
sed -i "/^\[$section\]/,/^\[/ s/^$key=.*/$key=$value/" $config_file
fi
Python 提供了 configparser
模块来处理 INI 文件。
读取 INI 文件
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
host = config['database']['host']
print(f"Host: {host}")
写入 INI 文件
import configparser
config = configparser.ConfigParser()
config['database'] = {'host': 'new_host', 'port': '3306'}
with open('example.ini', 'w') as configfile:
config.write(configfile)
sudo
提升权限。通过以上方法和注意事项,可以有效地管理和维护Linux INI文件。
领取专属 10元无门槛券
手把手带您无忧上云