根据IF条件读取多行

时间:2016-04-25 13:28:59

标签: bash awk sed

我有一个包含这些数据的非常大的文件:

qry> /opt/ADL_db/Users/mkhalil/PipeLineWork/2-OutputPlatesTest/20150615_053914.455_0_Front.Frontview.png
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_055509.656_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_083627.005_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_054920.969_0_Front.Frontview.png       (99%)

qry> /opt/ADL_db/Users/mkhalil/PipeLineWork/2-OutputPlatesTest/20150615_054239.612_0_Front.Frontview.png
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_060212.816_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_091652.202_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_081529.893_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_061203.680_0_Front.Frontview.png       (99%


qry> /opt/ADL_db/Users/mkhalil/PipeLineWork/2-OutputPlatesTest/20150615_054241.898_0_Front.Frontview.png
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_055047.746_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_061414.016_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_054643.282_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_090622.440_0_Front.Frontview.png       (99%)
cls> /opt/ADL_db/Users/mkhalil/PipeLineWork/1-OutputPlatesReference/20150612_083110.342_0_Front.Frontview.png       (99%)

我想读的只是qry>线和它后面的第一行,我不知道如何使用awk或sed或bash

2 个答案:

答案 0 :(得分:2)

您可以使用带有grep标记的GNU -A获取该行及其后面的行

grep -A1 'qry>' <filename>

将与包含qry>-A标记的行匹配,也会告诉它在匹配后也会抓住1行。

或者你可以使用sed更像POSIX-ly,如:

sed -n '/qry>/ {p;n;p;}' <filename>

以下是它的工作原理:

  • -n告诉sed不要打印行,除非我们明确这样做
  • /qry>/匹配包含该字符串的行
  • {p;n;p;}打印当前行(匹配qry>的那一行),转到n分机行,然后打印那行

要在纯粹的bash中进行操作,这样你就可以更容易地在线上操作

while read -r cur; do
    if [[ "$cur" =~ 'qry>' ]]; then
        read -r result
        # Do something here with the query in $cur and the first line in $result
        printf "query line: %s\nnext line: %s\n" "$cur" "$result"
    fi
done < your_input_file

答案 1 :(得分:0)

You can use awk:

$ awk 'BEGIN{flag=0} flag{print;flag=0} /qry>/{print;flag=1}' <filename>