我有以下文件:
$ cat animals
All birds
------------------------------------------------------------------------------
Birds in database size date
------------------------------------------------------------------------------
Pink flamingos 77 20130830
Black crows 997 20070122
All mammals
------------------------------------------------------------------------------
Mammals in database size date
------------------------------------------------------------------------------
brown cats 34 20111201
purple hippos 23 20120220
white dogs 9 20130926
black horses 2 20050428
pink monkeys 118 19940203
All reptiles
------------------------------------------------------------------------------
Reptiles in database size date
------------------------------------------------------------------------------
red snakes 44 20070125
green frogs 1022 20140707
$
我只想打印Mammals in database
部分的内容,即输出需要:
brown cats 34 20111201
purple hippos 23 20120220
white dogs 9 20130926
black horses 2 20050428
pink monkeys 118 19940203
我可以使用sed
:
$ gsed -n '/Mammals in database/,/^$/ { /Mammals in database/N; /Mammals in database/d; /^$/d; p }' < animals
brown cats 34 20111201
purple hippos 23 20120220
white dogs 9 20130926
black horses 2 20050428
pink monkeys 118 19940203
$
然而,是否有一种优雅的方式来实现与bash相同的效果?
答案 0 :(得分:3)
我喜欢使用awk
:
$ awk '!NF{f=0} NF>3 && f; /Mammals in database/ {f=1}' file
brown cats 34 20111201
purple hippos 23 20120220
white dogs 9 20130926
black horses 2 20050428
pink monkeys 118 19940203
这是一个标志f
的问题,并根据条件处理它开启或关闭。
纯粹的bash草案方法:
var=""
while read -r line
do
[[ $line =~ ^"All reptiles"* ]] && var=""
[ "$var" ] && [ "$line" ] && echo "$line"
[[ $line =~ ^"Mammals in database"* ]] && var=1
done < file
$ while read -r line ; do [[ $line =~ ^"All reptiles"* ]] && var=""; [ "$var" ] && [ "$line" ] && echo "$line"; [[ $line =~ ^"Mammals in database"* ]] && var=1; done < file
------------------------------------------------------------------------------
brown cats 34 20111201
purple hippos 23 20120220
white dogs 9 20130926
black horses 2 20050428
pink monkeys 118 19940203