【问题标题】:sed to read one file and delete pattern in second filesed 读取一个文件并删除第二个文件中的模式
【发布时间】:2014-01-07 09:22:46
【问题描述】:

我有一个在过去 180 天内登录的用户列表和一个来自 LDAP 的总用户列表。每个列表都在文本文件中,每个名称都在自己的行中。使用 sed 或 awk,我可以从 current-users.txt 中读取脚本并从 total-users.txt 中删除,从而给我一个包含过去 180 天所有非活动帐户的文本文档吗?

提前致谢!

【问题讨论】:

    标签: bash sed awk grep


    【解决方案1】:

    不需要 sed 或 awk,grep 就足够了:

    grep -vf current-users.txt total-users
    

    它返回所有在total_users 中但不在current-users.txt 中的行。

    • grep -f 从文件中获取参数。
    • grep -v 反转结果。

    示例

    $ cat total_users 
    one
    two
    three
    four
    
    $ cat some_users 
    two
    four
    
    $ grep -vf some_users total_users 
    one
    three
    

    【讨论】:

    • 太棒了,容易多了。谢谢!
    • 很高兴阅读。这不正是你所需要的吗?例如,您可以考虑在 grep 中添加 -w 以匹配完整的单词。
    【解决方案2】:

    使用 awk

    awk 'NR==FNR{a[$1];next} !($1 in a)' current_users total_users
    

    【讨论】:

    • 其实这样更准确。
    猜你喜欢
    • 2014-05-09
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多