bash - 删除 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/
解决方案
请您尝试以下方法:
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)
请注意提取变量名的解析器是一个糟糕的解析器。您可能需要根据实际文件调整代码。
推荐阅读
- php - 添加 Google auth 2.0 应用程序需要什么范围?
- mongodb - MongoDB Shell - 打印数组的第一个元素
- html - 如何将文本元素设置为 0px 宽度?
- r - R从gam中提取时变平滑参数
- assembly - 在指令周期的获取阶段,事情是如何工作的?
- angular - 调用同级方法会引发“无法读取未定义的属性 'X'”
- typescript - 是否有在适当位置键入对象的简写?
- mysql - SQLSTATE [42S22]:找不到列:1054 'where 子句'(SQL 更新..)中的未知列 'id',其中 'id' 为空)
- json - 如果等于 json,则 SOAPUI 断言 json 响应
- angular - TransferState:谁保证数据已经存储在状态中?