
1つのセクションに「something」で始まるフィールドを持つサンプルデータセットがあります。特定の文字列「1234」と一致するときは、各「何か」セクションのすべての行を取得したいと思います。
私は「1234」を検索し、「何か」が一致するまでその前後のすべての行を印刷できると思いました。
希望の出力:
something like this one
1234
abcd
something like this one
zyxw
1234
データセットの例:
otherthings
otherthings
otherthings
something like this one
1234
abcd
something not like this one
xxxx
yyyy
something not like this one
xxxx
yyyy
something like this one
1234
abcd
otherthings
otherthings
otherthings
答え1
「awk」を使う:
#!/bin/sh
awk '
function print_section() {
# Only print section if "1234" was encountered
if (valid == 1) print section;
}
{
if (/something/) {
# Start new section
section = $0;
}
else if (/^\s*$/) {
# Empty line -> output previous section
if (section ne "") {
print_section();
section = "";
valid = 0;
}
}
else if (section ne "") {
# Add line to section if one has been started
section = section "\n" $0;
if (/1234/) valid = 1;
}
}
END {
# End of file, print current section if it exists
print_section();
}
' file