图案后提取字符串 [英] extract a string after a pattern

查看:128
本文介绍了图案后提取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要提取以下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="[\(\):,]"}: invoke awk, use ( ) : and , as delimiters to separate your fields
  • /client_id/ {: Only do the following for the lines that contain client_id:
  • for (i=1; i<NF; i++) {: iterate through the fields on each line one field at a time
  • if ($i == "client_id") { cid = $(i+1) }: if the field we are currently on is client_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 is id, then print the client_id : id pair onto stdout
  • input_file_name: supply the name of your input file as first argument to the awk script.

这篇关于图案后提取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆