如果下一行匹配,则使用awk打印行+下两行

时间:2016-12-14 23:43:22

标签: awk

我有一个这样的列表来捕捉joomla版本

./somedir/bla/old/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '24';
./somedir/bla3/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';
./somedir/bla4/www/libraries/cms/version/version.php
./somedir/bla5/www/w/scripts/version.php
./somedir/bla6/www/libraries/cms/version/version.php
./somedir/bla7/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';

我想要的是,如果public位于下一行,则仅显示第二行和下两行。必须忽略其他行

所以结果应该是:

./somedir/bla/old/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '24';
./somedir/bla3/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';
./somedir/bla7/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';

我曾尝试使用Awk和这个awk脚本

BEGIN{ RS=""; FS="\n" }
 /public/ {
    for (i=1; i<=NF; i++) {
        if ( ! (($i ~ /./) && ($(i+1) !~ /public/) && ($(i+2) !~ /public/) ) ) {
            print $i
        }
    }
    print ""
}

但结果是:

./somedir/bla/old/libraries/cms/version/version.php
        public $RELEASE = '2.5';
./somedir/bla3/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
./somedir/bla7/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';

我错过了dev_level

的第二个公共线路

2 个答案:

答案 0 :(得分:3)

你打算通过考虑打印接下来会发生的事情而难以做到这一点(很难做到,因为你还没有看到它!)而不是打印之前的事情(很容易做到 - 只需保存并打印出来):

$ awk '/public/{print p $0; p=""; next} {p=$0 ORS}' file
./somedir/bla/old/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '24';
./somedir/bla3/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';
./somedir/bla7/www/libraries/cms/version/version.php
        public $RELEASE = '2.5';
        public $DEV_LEVEL = '9';

任何时候你发现自己试图根据后面的内容弄清楚如何处理当前行,在你处理未来行时,花点时间重新思考一下(所以IT然后是基于前面的内容的当前&#34;线。在软件和生活中 - 看到未来比记住过去困难得多!

答案 1 :(得分:1)

使用grep

尝试

grep 'public $DEV' -B 2 yourfile.txt

来自man grep

 -B NUM, --before-context=NUM
     Print NUM lines of leading context before matching lines.  
     Places a line containing a group separator (--) between contiguous groups of matches.