【问题标题】:Bash script to remove some keywords in a txt file用于删除 txt 文件中的某些关键字的 Bash 脚本
【发布时间】:2022-01-04 06:13:05
【问题描述】:

我对bash脚本不熟悉,经过一番研究,我发现了一些提示,但仍然需要你的努力。

鉴于我有一个 resources.txt,包含

a
b
c
d

还有一个whitelist.txt文件,包含

c
d

我想删除从白名单文件到资源文件中完全匹配的所有项目。 所以预期的输出是

a
b

期望 c 和 d 被删除,因为它们在白名单文件中。

我创建了下面的脚本来读取它,但不知道如何将每个替换为资源文件。

# read the whitelist file
echo whitelist.txt | awk '{for (i=1; i<=NF; i++) printf "%s\n",$i}

# replace item in resource file
awk '{sub(/c/,""); print}' resources.txt

非常感谢您的帮助,非常感谢!

【问题讨论】:

  • 假设文件已排序,comm -23 resources.txt whitelist.txt
  • @Shawn 因为列表是动态的,所以使用预定义/硬编码索引不是一个现成的解决方案 :( ,顺便说一句,非常感谢您抽出宝贵的时间!

标签: bash awk sed xargs


【解决方案1】:

我会使用这个 grep:

grep -Fvxf whitelist.txt resources.txt
  • -F 固定/文字字符串(无正则表达式)
  • -f FILE 从 FILE 中获取模式
  • -x匹配整行
  • -v 打印匹配的行
  • 这个grep是POSIX

【讨论】:

    【解决方案2】:

    使用awk你可以使用

    awk 'FNR==NR{a[$0];next}!($0 in a)' whitelist.txt resources.txt
    

    部分

    awk '
    FNR==NR{                       # Only for the first file (whitelist.txt)
      a[$0]                        # Set the value of the whole line as a key in a
      next                         # Go to the next record
    }
    !($0 in a)                     # Print the line if the value of `$0` does not exists as array index in a
    ' whitelist.txt resources.txt
    

    输出

    a
    b
    

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 2023-03-23
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      相关资源
      最近更新 更多