【问题标题】:Remove duplicate variables except last occurrence in bash script file删除 bash 脚本文件中除最后一次出现的重复变量
【发布时间】:2021-03-12 05:43:54
【问题描述】:

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

#!/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/

【问题讨论】:

  • 所以不是追加,而是覆盖文件。
  • 这能回答你的问题吗? How do I delete an exported environment variable?
  • 不清楚您在寻找什么。您能否提供一个示例,说明您在更新前看到的内容以及更新后的预期内容?
  • department=(Production R&D) 是语法错误。你需要一些引号。
  • is getting appended from the remote hosts where I cannot access the file to overwrite 如果你可以追加(你对文件有写权限),你可以覆盖(在 99.99% 的情况下)。 Appending is done by redirecting the sshpass output the file 太好了!所以不要使用>>,而是使用>

标签: bash shell duplicates


【解决方案1】:

请您尝试以下方法:

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)

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

【讨论】:

  • 感谢您的反馈。您不能使用重定向覆盖文件。请重定向到另一个文件名,例如file2,然后将其重命名为mv -f file2 file。祝你好运!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
  • 2016-10-11
  • 2022-11-22
  • 2015-05-27
  • 1970-01-01
  • 2022-11-19
相关资源
最近更新 更多