【问题标题】:Bash get uniq elements and filter the valuesBash 获取唯一元素并过滤值
【发布时间】:2017-04-26 05:47:11
【问题描述】:

bash 新手。 我有一个文本文件 test.txt,其中有两个键,一个是 user_type,另一个是 user。目前user_type有两种类型的值,“admin”或“guest”,user可以有任何类型的值

     {  user_type: admin
        user: john    
             }
     { user_type: guest
       user: doe               
      }

     {user_type: admin
      user: test 
         }

     { user_type: admin
       user: something 
       } ........

我正在尝试使用 user_type 获取 uniq 值

    cat man.txt|sort|uniq    

但它似乎不起作用。

  1. 如何获取与 user_type 键关联的 uniq 值?

2.如何根据users过滤值并计算user_type值?我有一个有值的数组

 array = (doe,test)  #This array can have any values from the user values of man.txt

注意:这个数组是从一个 api 请求生成的,它有一些选择“用户”的标准,我只想计算与数组中的值关联的 user_type 值

现在我只想要与该数组关联的 user_type 值。 并计算特定类型重复多少次的 user_types 值。

 for i in ${array[@]};do
     grep -c $i man.txt

但它正在返回输出:

     user:doe
  or user:test

但它不返回 user_type 的特定值的计数?

【问题讨论】:

  • 感谢指出。我已修复
  • 能否详细解释一下2)数组是如何形成的,不清楚
  • 这是一个损坏的JSON 文件吗?
  • 我解释了数组的形成。实际上 JSON 文件是我使用“some API request”|jq '.[]|{"user_type": .user_type,"user" 从 API 请求生成的: .group.user}
  • 如果您对jq 感到满意,那么为什么要使用grep

标签: arrays linux bash shell unix


【解决方案1】:

如果您可以确定文件中的行始终按以下顺序排列:user_typeuser,那么您可以执行以下操作:

array=("test" "doe")
for username in "${array[@]}"; do
    grep -B1 "$username" man.txt | grep -o 'user_type:.*' | sort | uniq -c
done

grep -B1 在匹配项上方输出一行,然后我们匹配它以仅获得user_type 输出,管道到sort 并使用uniq 计算行数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-11
    • 2015-05-22
    • 2013-06-22
    • 2021-02-22
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多