Grepping stdout 以获得特定的字符串,同时避免重复

Grepping stdout to attain specific strings, while avoiding repeats

我试图 grep 命令的标准输出以仅显示两个字符串之间的结果。我想从 'Alias' 的第一个案例打印到 'Valid' 的第一个案例,然后再次重复。

标准输出:(“<---”仅用于显示我要打印的行)

foo
bar
Alias: Name                        <---
fo bar
foo bar
Valid from: Monday Until: Thu May 26 12:44:38         <---
Valid from: Tuesday Until: Fri Nov 27 22:41:01 
Alias: Another_Name                                   <---
Valid from: Wednesday Until: Fri Nov 27 22:41:01         <---
Valid from: Friday Until: Thu Dec 04 23:31:58
Foo bar 
bar foo 

管道预期输出:

Alias: Name 
Valid from: Monday Until: Thu May 26 12:44:38
Alias: Another_Name 
Valid from: Wednesday Until: Fri Nov 27 22:41:01

我尝试过的事情:

命令 | egrep "Alias:|Valid" #这也捕获了第二个'valid' 命令 | grep -P "Alias*|Valid*" #This 再次捕获第二个 'valid..'

如有任何帮助,我们将不胜感激!

编辑: 在与 OP 讨论后,以下代码适用于 OP。在 GNU awk.

中编写和测试
awk -v IGNORECASE="1" '
/alias/{
  count=0
  aliasVal=[=10=]
  next
}
aliasVal && /valid/ && ++count==1{
  print aliasVal ORS [=10=]
}
' Input_file

这可以在awk程序中完成,请尝试以下一次。仅使用您展示的示例编写和测试。

awk '
/Alias:/{
  count=0
  aliasVal=[=11=]
  next
}
aliasVal && /Valid from:/ && ++count==1{
  print aliasVal ORS [=11=]
}
'   Input_file

解释:为以上添加详细解释。

awk '                      ##Starting awk program from here.
/Alias:/{                  ##Checking if line contains Alias: then do following.
  count=0                  ##Setting count to 0 here.
  aliasVal=[=12=]              ##Setting aliasVal variable to current line value here.
  next                     ##Skipping all further statements from here.
}
aliasVal && /Valid from:/ && ++count==1{  ##Checking if aliasVal is set AND line contains Valid from: AND count is 1 then do following.
  print aliasVal ORS [=12=]    ##Printing aliasVal ORS and current line here.
}
' Input_file               ##Mentioning Input_file name here.


为了 运行 在 bash 脚本中尝试这样的事情:

cat script.bash
#!/bin/bash
awk '
/Alias:/{
  count=0
  aliasVal=[=13=]
  next
}
aliasVal && /Valid from:/ && ++count==1{
  print aliasVal ORS [=13=]
}
'   Input_file

然后给脚本适当的权限,运行它。

要从命令行 运行 它,您可以 运行 在非一个班轮代码之上,或者直接在终端本身上跟随一个班轮代码。

awk '/Alias:/{count=0;aliasVal=[=16=];next} aliasVal && /Valid from:/ && ++count==1{print aliasVal ORS [=16=]}' Input_file

这可以使用简单的 sed:

sed -n '/^Alias:/,/^Valid from:/ {//p;}' file

Alias: Name
Valid from: Monday Until: Thu May 26 12:44:38
Alias: Another_Name
Valid from: Wednesday Until: Fri Nov 27 22:41:01

也许是这样的:

awk -F: '==(f ? "Valid from" : "Alias name") {print; f=!f}'

拆分 :,当 $1 是预期值时打印(通过翻转变量来交替)。

或者 sed 可以使用其范围运算符,后跟其特殊的空正则表达式地址(使用最近使用的正则表达式)

sed '/^Alias name:/,/^Valid from:/!d;//!d'
$ awk '/^Alias/{print; f=0} /^Valid/ && !f++' file
Alias: Name                        <---
Valid from: Monday Until: Thu May 26 12:44:38         <---
Alias: Another_Name                                   <---
Valid from: Wednesday Until: Fri Nov 27 22:41:01         <---