Linux shell脚本:如何将子字符串与正则表达式匹配

时间:2013-11-28 08:10:59

标签: regex linux shell substring

如何获得“client_type = 0”的所有“clid”?管道字符“|”分离每个客户信息。我的文字只有一行:

  

clid = 2 cid = 3346 client_database_id = 5153 client_nickname = xLukas \ s \ p \ sLukas client_type = 0 | clid = 3 cid = 3346 client_database_id = 1 client_nickname = powered \ sby \ sMirWayne.DE   client_type = 1 | clid = 4 cid = 3346 client_database_id = 9661   client_nickname = Number \ sone client_type = 0 | clid = 5 cid = 3469   client_database_id = 1 client_nickname = powered \ sby \ sMirWayne   client_type = 1 | clid = 6 cid = 1716 client_database_id = 1   client_nickname = FG \ sBot client_type = 1 | clid = 7 cid = 3469   client_database_id = 9661 client_nickname = Number \ stwo   client_type = 0 | clid = 8 cid = 1762 client_database_id = 4351   client_nickname = pr0zkillz1x \ pTobi client_type = 0 | clid = 9 cid = 1764   client_database_id = 5160 client_nickname = xL1mited \ s / \ sMax   client_type = 0 | clid = 10 cid = 1716 client_database_id = 9704   client_nickname = Sebi client_type = 0 | clid = 13 cid = 3346   client_database_id = 4336 client_nickname = checker284 \ s \ p \ sSebbo   client_type = 0 | clid = 19 cid = 1762 client_database_id = 9312   client_nickname = pr0skillz1x \ pDanie client_type = 0 | clid = 30 cid = 3346   client_database_id = 9697 client_nickname = TeamSpeakUser   client_type = 0 | clid = 33 cid = 1716 client_database_id = 1   client_nickname = serveradmin client_type = 1

我需要alle clid,它在额外的行中有client_type = 0。例如:

    clid=2
    clid=3
    clid=4
    clid=5
    ...

我目前的解决方案无效:

    cat clientlist.txt | grep -Eo "clid=[0-9]+[\d\D]*client_type=0" | grep -Eo "clid=[0-9]+"

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

使用sed:

tr '|' '\n' < file | sed -n '/client_type=0/s/\(clid=[0-9]*\).*$/\1/p'
clid=2
clid=4
clid=7
clid=8
clid=9
clid=10
clid=13
clid=19
clid=30

答案 1 :(得分:1)

  

管道字符“|”分离每个客户信息。

利用这些信息,您可以说:

tr '|' '\n' < clientlist.txt | grep -Po 'clid=\d+(?=.*client_type=0)'

对于您的输入,结果是:

clid=2
clid=4
clid=7
clid=8
clid=9
clid=10
clid=13
clid=19
clid=30