sed两个字符串之间的模式匹配仅显示第一个匹配

时间:2017-09-05 12:08:55

标签: awk sed

我正在尝试使用两个字符串之间的sed模式匹配来解析文件并找到第一个匹配,使用第一个匹配,我试图在循环中迭代执行某些操作,两个字符串之间的sed模式匹配打印所有的比赛,我只是想得到第一场比赛:

档案:

  },{
   "prefix" : "AD",
   "prefix" : "CQ",
   "last" : 0,
   "last" : 0,
   "month" : 0,
   "month" : 5,
   "today": 0,
   "today": 0,
   "yesterday": 2,
   "yesterday": 0,
   "agents": 0
  },{
   "prefix" : "CS",
   "prefix" : "AE",
   "last" : 1,
   "last" : 0,
   "month" : 130,
   "month" : 0,
   "today": 0,
   "today": 20,
   "yesterday": 0,
   "yesterday": 38,
   "agents": 0
  },{
   "prefix" : "AF",
   "prefix" : "CZ",
   "last" : 0,
   "last" : 0,
   "month" : 6,

我试图在前缀和代理之间进行提取,但只使用下面的sed命令进行第一次匹配:

sed -n '/prefix/,/agents/p' /var/saas/stats/usage_1499245200.json.2 >> /var/saas/stats/try

有没有办法我只能在第一次迭代usage_1499245200.json.2中从文件中提取第一个匹配项并执行循环。

谢谢, Sriram.V

2 个答案:

答案 0 :(得分:2)

使用awk

[akshay@localhost test]$ awk '/prefix/{found=1}found;/agents/{exit}' infile
   "prefix" : "AD",
   "prefix" : "CQ",
   "last" : 0,
   "last" : 0,
   "month" : 0,
   "month" : 5,
   "today": 0,
   "today": 0,
   "yesterday": 2,
   "yesterday": 0,
   "agents": 0

<强> 输入

[akshay@localhost test]$ cat infile
},{
   "prefix" : "AD",
   "prefix" : "CQ",
   "last" : 0,
   "last" : 0,
   "month" : 0,
   "month" : 5,
   "today": 0,
   "today": 0,
   "yesterday": 2,
   "yesterday": 0,
   "agents": 0
  },{
   "prefix" : "CS",
   "prefix" : "AE",
   "last" : 1,
   "last" : 0,
   "month" : 130,
   "month" : 0,
   "today": 0,
   "today": 20,
   "yesterday": 0,
   "yesterday": 38,
   "agents": 0
  },{
   "prefix" : "AF",
   "prefix" : "CZ",
   "last" : 0,
   "last" : 0,
   "month" : 6,

答案 1 :(得分:1)

您可以在遇到agents时添加退出命令:

sed -n -e '/prefix/,/agents/p' -e '/agents/q'

结果:

   "prefix" : "AD",
   "prefix" : "CQ",
   "last" : 0,
   "last" : 0,
   "month" : 0,
   "month" : 5,
   "today": 0,
   "today": 0,
   "yesterday": 2,
   "yesterday": 0,
   "agents": 0