【问题标题】:Using sed to separate pattern from stream使用 sed 将模式与流分离
【发布时间】:2013-12-19 09:13:00
【问题描述】:

我有一个在每一行都有日志条目的文件,例如:

request country_US url=http://example.com/us/id=6546456 {response_time 1000 msec} 
request country_UK url=http://example.com/uk/id=1242423 {response_time 60 msec} 

现在我正在使用 sed 来处理这个文件并将响应时间分开,如下所示:

sed -e 's/.*\(response_time \S\+\).*/\1/p' -e 's/'

将每一行转换为

response_time 1000
response_time 60

现在我还想分开国家前缀并像这样处理行:

US 1000
UK 60

我应该如何修改我的 sed 命令? 谢谢!

【问题讨论】:

    标签: regex bash file unix sed


    【解决方案1】:

    试试这个:

    sed -e 's/^request country_\([^ ]*\).*response_time \([0-9]*\) msec.*$/\1 \2/g'
    

    【讨论】:

      【解决方案2】:

      您可以稍微修改您的sed 表达式以获得所需的结果。说:

      sed -r 's/.*country_(\S+).*response_time ([0-9]+).*/\1 \2/' filename
      

      将为您的示例输入返回以下内容:

      US 1000
      UK 60
      

      【讨论】:

        【解决方案3】:

        使用awk

        awk '/response_time/ {split($2,a,"_");print a[2],$(NF-1)}' file
        US 1000
        UK 60
        

        如果所有行都有response_time,你可以这样做:

        awk '{split($2,a,"_");print a[2],$(NF-1)}' file
        

        或者只是:

        awk -F" |_"  '{print $3,$7}' file
        US 1000
        UK 60
        

        【讨论】:

          【解决方案4】:

          与您的原始版本几乎相同的另一种可能性是:

          sed -e 's/.*country_\(\S\+\).*response_time\( \S\+\).*/\1\2/' file
          US 1000
          UK 60
          

          对于未来我只能推荐http://vimregex.com/。我一直觉得它非常有用。

          【讨论】:

            猜你喜欢
            • 2016-04-21
            • 2016-12-11
            • 2018-11-04
            • 1970-01-01
            • 2021-05-23
            • 1970-01-01
            • 1970-01-01
            • 2016-05-06
            • 2012-02-21
            相关资源
            最近更新 更多