bash获取uniq元素并过滤值



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.如何根据用户过滤值,并计数 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

,但它不会返回用户_type的特定值的计数?

如果您可以确定该文件始终在顺序中: 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进行计数。

最新更新