图案后提取字符串 [英] extract a string after a pattern
本文介绍了图案后提取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要提取以下CLIENT_ID和ID的数量和配对的client_id和id每行。
I want to extract the numbers following client_id and id and pair up client_id and id in each line.
例如,对于日志的以下行,
For example, for the following lines of log,
User(client_id:03)) results:[RelatedUser(id:204, weight:10),_RelatedUser(id:491,_weight:10),_RelatedUser(id:29, weight: 20)
User(client_id:04)) results:[RelatedUser(id:209, weight:10),_RelatedUser(id:301,_weight:10)
User(client_id:05)) results:[RelatedUser(id:20, weight: 10)
我要输出
03 204
03 491
03 29
04 209
04 301
05 20
我知道我需要使用awk或者sed。但我不知道到底怎么样。
I know I need to use sed or awk. But I do not know exactly how.
感谢
推荐答案
下面是一个 AWK
脚本作品(我把它放在多行,并使其更有点冗长所以你可以看到这是怎么回事):
Here's a awk
script that works (I put it on multiple lines and made it a bit more verbose so you can see what's going on):
#!/bin/bash
awk 'BEGIN{FS="[\(\):,]"}
/client_id/ {
cid="no_client_id"
for (i=1; i<NF; i++) {
if ($i == "client_id") {
cid = $(i+1)
} else if ($i == "id") {
id = $(i+1);
print cid OFS id;
}
}
}' input_file_name
输出:
03 204
03 491
03 29
04 209
04 301
05 20
说明:
-
的awk'BEGIN {FS =[\\(\\):,]}
:调用AWK
,使用(
)
:
和 -
/ CLIENT_ID / {
:只有做包含的client_id
线以下内容: -
为(i = 1; I&LT; NF;我++){
:通过在每行一个字段的字段重复一次 -
如果($ I ==的client_id){CID = $(I + 1)}
:如果字段我们目前是CLIENT_ID
,那么它的值是下一个现场秩序。 -
否则如果($ I ==ID){ID = $(I + 1);打印CID OFS ID;}
:反之领域,我们目前正在对为ID
,然后打印CLIENT_ID:ID
对到标准输出
-
input_file_name
:电源输入文件作为第一个参数AWK
脚本的名称
awk 'BEGIN{FS="[\(\):,]"}
: invokeawk
, use(
)
:
and,
as delimiters to separate your fields/client_id/ {
: Only do the following for the lines that containclient_id
:for (i=1; i<NF; i++) {
: iterate through the fields on each line one field at a timeif ($i == "client_id") { cid = $(i+1) }
: if the field we are currently on isclient_id
, then its value is the next field in order.else if ($i == "id") { id = $(i+1); print cid OFS id;}
: otherwise if the field we are currently on isid
, then print theclient_id : id
pair ontostdout
input_file_name
: supply the name of your input file as first argument to theawk
script.
这篇关于图案后提取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文