[英]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.