开发者

Any tool for easily parse a config file on Linux?

I need a tool that allows me to parse a config file and request some data from it.

The format of the config file is free (it can be INI, XML, and so on) but the more human-friendly, the better.

Here is a sample config file (using X开发者_如何学编程ML, but it could be anything: i don't mind the format):

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
  <name>Some name</name>
  <description>Some description</description>
</configuration>

The tool usage should be something like:

[ereOn@server ~]$ the_tool config.xml "string(/configuration/name)"
Some name
[ereOn@server ~]$ the_tool config.xml "string(/configuration/description)"
Some description

Do you know any Linux tool that can do that ?


You could do that with python (.ini-Style config files): http://docs.python.org/library/configparser.html

EDIT: You could just use sed with regexes, too (but forget the "easily" then, if you're not experienced a bit with sed :P).


A simple config format style (variable=value, one per line) is easily parsed with grep and cut.

For example config.conf file:

name=Some Name
description=Some Description

Then to get a specific value:

# grep "^name=" config.conf | cut -d= -f2
Some Name
# grep "^description=" config.conf | cut -d= -f2
Some Description

It's easy and very cheap (doesn't require any additional binaries to be installed as grep and cut are standard on any Linux...).

You could also write a simple bash script wrapper if you want a single command to provide the value you need:

#!/bin/bash

CONFIG_PATH=/path/to/config.conf

if [ ! -e $CONFIG_PATH ]; then
  echo "$CONFIG_PATH not found"
  exit 1
fi

if [ $# -ne 1 ]; then
  echo "Syntax: $0 \"<variable name>\""
  exit 1
else
  VARNAME="$1"
  eval "grep \"^$VARNAME=\" $CONFIG_PATH | cut -d= -f2"
fi

Then all you need to do is call it like this:

# yourscript.sh variable_name


Perl has modules for many different formats of config file including JSON and INI

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜