Grep characters before and after match?

前端 未结 7 1498
长情又很酷
长情又很酷 2020-12-02 04:19

Using this:

grep -A1 -B1 \"test_pattern\" file

will produce one line before and after the matched pattern in the file. Is there a way to di

相关标签:
7条回答
  • 2020-12-02 05:08

    With gawk , you can use match function:

        x="hey there how are you"
        echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
        ere   are
    

    If you are ok with perl, more flexible solution : Following will print three characters before the pattern followed by actual pattern and then 5 character after the pattern.

    echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
    ey there how
    

    This can also be applied to words instead of just characters.Following will print one word before the actual matching string.

    echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
    hey
    

    Following will print one word after the pattern:

    echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
    how
    

    Following will print one word before the pattern , then the actual word and then one word after the pattern:

    echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
    hey there how
    
    0 讨论(0)
提交回复
热议问题