如何搜索用户所属的特定组

时间:2017-09-07 12:51:31

标签: linux awk sed

我有文件test.txt,其中包含id命令的详细信息(例如:id sudi

uid=23351(sudi) gid=5000(bns) groups=5000(bns),16382(damepgrp),15657(edl_prd_rcrr_sup),15650(edl_prd_rcrr_user),15712(edl_prd_yarn_int_cb),15721(edl_prd_yarn_int_rsk),15632(edl_prod_rcam_admin),16110(edlp_bc5m_sup)

uid=23458(achung1) gid=5000(bns) groups=5000(bns),15757(edl_prd_ice_analyst),15483(edl_prd_ice_user),15650(edl_prd_rcrr_user),15712(edl_prd_yarn_int_cb),15721(edl_prd_yarn_int_rsk)

uid=19831(afabia) gid=5000(bns) groups=5000(bns),15774(edl_prd_c360da_users),15714(edl_prd_yarn_int_ana),15712(edl_prd_yarn_int_cb),15606(edl_prod_c360_users),16179(edl_prod_c360rt_users),15621(edl_prod_dspm_dev),16076(edlp_bc4g_ca_ez_usr),16052(edlp_bc4g_ca_usr),16053(edlp_c360_da_usr),15105(hdpcmo),15104(hdpnanalytics),15279(hdpnaug),15144(rscmo),15280(rsnaug),16171(edl_prod_c360rt_susr)

如何仅打印id和yarn组作为输出。我用grep和sed尝试过但没有运气 例如:

 sudi: edl_prd_yarn_int_ana, edl_prd_yarn_int_cb
 achung1: edl_prd_yarn_int_cb, edl_prd_yarn_int_rsk
 afabia: edl_prd_yarn_int_cb, edl_prd_yarn_int_ana

2 个答案:

答案 0 :(得分:0)

使用

gawk

$ awk -v RS='[()]' -v OFS=, '/yarn/{s=s?s OFS $1:$1}END{print "sudi: " s}' infile
sudi: edl_prd_yarn_int_ana,edl_prd_yarn_int_cb

awk

$ awk -F'[()]' -v OFS=, '{for(i=1; i<=NF; i++)if($i~/yarn/)s=s?s OFS $i:$i}END{print "sudi: " s}' infile

<强> 输入:

$ cat infile
uid=21015(sudi) gid=5000(bns) groups=5000(bns),15714(edl_prd_yarn_int_ana),15712(edl_prd_yarn_int_cb),16083(edlp_bc4g_sup),16186(edlp_bc55_ah_da_usr1),16183(edlp_bc55_ah_da_usr2),16134(edlp_bc55_sup),16045(edlp_ds_na_usrgrp),15970(edlp_dsci_usr),15861(edlp_dsna_app),15956(edlp_pricinggtb_susr),15105(hdpcmo),15108(hdpcoe),15104(hdpnanalytics),15144(rscmo),15143(rsnanalytics),15152(rsnanalyticssec),15159(s2hdp19grp)

答案 1 :(得分:0)

grep -oP "uid=\d+\(\K\w+(?=\))|\w+yarn\w+" file | awk '$0~/yarn/{if(!first){a=a" "$1; first=1}else{a=a" ,"$0}} $0!~/yarn/{print a; a=$0":"; first=0} END{print a}'

输出:

sudi: edl_prd_yarn_int_cb,edl_prd_yarn_int_rsk
achung1: edl_prd_yarn_int_cb,edl_prd_yarn_int_rsk
afabia: edl_prd_yarn_int_ana,edl_prd_yarn_int_cb