首页 > 解决方案 > 删除 bash 脚本文件中除最后一次出现的重复变量

问题描述

我在本地有配置文件,我从不同的远程机器附加了一些变量。文件内容如下:

#!/bin/bash

name=bob
department=(Production)

name=alice
department=(R&D)

name=maggie
department=(Production R&D)

文件中更新的最新值是最后一个。所以配置文件中的预期输出应该是:

#!/bin/bash
name=maggie
department=(Production R&D)

我想删除姓名和地址的前两个数据,除了最后一个。但这只有在有多个相同变量时才会发生。

我参考并尝试了这个解决方案,但没有得到预期的输出: https ://backreference.org/2011/11/17/remove-duplicates-but-keeping-only-the-last-occurrence/

标签: bashshellduplicates

解决方案


请您尝试以下方法:

tac file | awk '{                               # print "file" reversing the line order: last line first
    line = $0                                   # backup the line
    sub(/#.*/, "")                              # remove comments (not sure if comment line exists)
    if (match($0, /([[:alnum:]_]+)=/)) {        # look like an assignment to a variable
        varname = substr($0, RSTART, RLENGTH - 1)
                                                # extract the variable name (-1 to remove "=")
        if (! seen[varname]++) print line       # print the line if the variable is seen irst time
    } else {                                    # non-assignment line
        print line
    }
}' | tac                                        # reverse the lines again

输出:

#!/bin/bash



name=maggie
department=(Production R&D)

请注意提取变量名的解析器是一个糟糕的解析器。您可能需要根据实际文件调整代码。


推荐阅读