简体   繁体   English

使用awk或sed删除字段以获取值

[英]Remove field to get the value using awk or sed

I have a text file with following data. 我有一个包含以下数据的文本文件。

            \ {
                Name     "ABC",
                count   378
            }
            \ {
                Name     "DEF",
                count   5283
            }
            \ {
                Name     "BCD",
                count   152244
            }
            \ {
                Name     "XYZ",
                count   5688
            }
            \ {
                Name     "1A2B",
                count   1749132
            }

I want the result like :-- 我想要这样的结果:-

            ABC , 378
            DEF , 5283
            BCD , 152244
            XYZ , 5688
            1A2B ,1749132

I tried to remove the non revelant data using the command :-- 我尝试使用以下命令删除非公开数据:-

            grep -e '^ ' result.txt 

But I am unable to proceed beyond it . 但是我无法超越它。 Can someone help me with same ? 有人可以帮我吗?

try following awk and let me know if this helps you. 尝试跟随awk,让我知道这是否对您有帮助。

awk '/Name/{gsub(/\"|\,/,"",$2);val=$2;next} /count/{print val " , " $2}'  Input_file

OR 要么

awk -F'[",]' '/Name/{val=$2;next} /count/{split($0, a," ");print val,a[2]}' OFS=" , "  Input_file

Here's another awk thought you may apply, 这里的另一个awk以为你可以申请,

$ awk '$2~/[0-9A-Z]/ {printf gsub(/"/,"",$2)?$2:" "$2"\n"}' file

Brief explanation, 简要说明,

  • $2~/[0-9A-Z]/ : find the record matched regex [0-9A-Z] $2~/[0-9A-Z]/ :找到与记录匹配的正则表达式[0-9A-Z]
  • gsub(/"/,"",$2) : remove " in the $2 , and then print it gsub(/"/,"",$2)除去"$2 ,然后将其打印

If you are using an awk that supports regular expression RS (at least gawk and mawk), you can do it like this: 如果您使用的是支持正则表达式RS的awk(至少是gawk和mawk),则可以这样做:

awk '!(NR%2) { print $3 " , " $5  }' RS='\\ *{|}' FS='[\n," ]+' infile

Output: 输出:

ABC , 378
DEF , 5283
BCD , 152244
XYZ , 5688
1A2B , 1749132

sed solution: sed解决方案:

sed -En '/[{}]/d;N; s/Name *"([^"]+)".*count *([0-9]+).*/\1 , \2/p;' file

The output: 输出:

        ABC , 378
        DEF , 5283
        BCD , 152244
        XYZ , 5688
        1A2B , 1749132

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM