![](/img/trans.png)
[英]Choose block print section of file between two regular expressions using sed or awk
[英]Print multiple-line section between two strings only if this section contains certain keyword using bash?
我有一个名为animals
的文件,其中包含以下条目:
$ cat animals
name: elephant
class: mammal
habitat: India
name: Baltic herring
class: fish
habitat: Baltic sea
name: wolf
class: mammal
habitat: Sweden
name: eagle
class: bird
habitat: USA
$
如上所示,该文件包含四个部分。 我只想打印那些包含字符串mammal
部分,并且我想用bash进行打印,即不要使用sed
或awk
。 我这样做是这样的:
$ cat animals | while read -r line; do
> if [[ "$line" =~ ^name ]]; then
> section="$line"
> while read -r line2; do
> if [[ "$line2" =~ ^$ ]]; then
> break
> else
> section+=$'\n'"$line2"
> fi
> done
> echo "$section" | grep -q mamm && echo "$section"$'\n' ; section=
> fi
> done
name: elephant
class: mammal
habitat: India
name: wolf
class: mammal
habitat: Sweden
$
但是,是否有一种更优雅(更短而不那么麻烦)的方式来实现bash? 还是在这一点上应该研究awk
工具?
一个简单的怎么样
grep mammal -C 1 --group-separator="" animals
是的,您应该研究awk。 它使您可以更简单地执行此操作:
awk -v RS= -v ORS='\n\n' '/mammal/' file
这将取消设置记录分隔符,以便将每个块都视为单个记录。 然后,它打印与模式“哺乳动物”匹配的每个记录,后跟两个换行符,产生与问题所示相同的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.