在 bash 中将标准 属性 文件中的 select 属性提取到单个分隔行?

In bash extract select properties from a standard property file to a single delimited line?

在bash中:

1) 对于 给定的 groupname 兴趣,并且
2) 一个 keys 感兴趣的列表,我们需要 table 个 ,为此 组名,
3) 读入 文件集 ,如 /usr/share/applications 中的文件(参见下面的简化示例)
4) 并生成一个带分隔符的 table,每个文件一行,每个给定键一个字段。


例子

输入

我们只需要 NameExec 键的值,仅来自 [Desktop Entry] 组,并且来自一个或更多文件,例如:

[Desktop Entry]
Name=Root
Comment=Opens
Exec=e2

..

[Desktop Entry]
Comment=Close
Name=Root2

输出

两行,每个输入文件一行,每行采用分隔 <Name>,<Exec> 格式,准备导入数据库:

Root,e2
Root2,

每个输入文件是:


[如果我要求解决一个老问题,请原谅我,但我似乎找不到一个好的、快速的 bash 方法来做到这一点。是的,我可以用一些 while 和 read 循环等来编写它……但肯定以前有人做过。]


类似于 但需要更笼统的答案。

如果 awk 是您的选择,请您尝试以下操作:

awk -v RS="[" -v FS="\n" '{     # split the file into records on "["
                                # and split the record into fields on "\n"
    name = ""; exec = ""        # reset variables
    if ( == "Desktop Entry]") {
                                # if the groupname matches
        for (i=2; i<=NF; i++) { # loop over the fields (lines) of "key=value" pairs
            if (sub(/^Name=/, "", $i)) name = $i
                                # the field (line) starts with "Name="
            else if (sub(/^Exec=/, "", $i)) exec = $i
                                # the field (line) starts with "Exec="
        }
        print name "," exec
    }
}' file

您可以将多个文件输入为 file1 file2 file3dir/file* 或其他格式。