grep: returning multiple lines

2021-06-07

 | 

~2 min read

 | 

269 words

I often find myself grepping files to quickly find data. Often times, however, I am as interested in the lines surrounding the one where I found my pattern as the line itself.

In the past, that often meant I’d open vim or an IDE to explore more in depth.

I was confident that grep would be able to handle this use case, if only I took the time to learn the API.

It turns out I was right! With the addition of a few flags (-A, -B, and -C), I could get exactly what I wanted.

From the manual:

     -A num, --after-context=num
             Print num lines of trailing context after each match.  See also
             the -B and -C options.

     -B num, --before-context=num
             Print num lines of leading context before each match.  See also
             the -A and -C options.

     -C[num, --context=num]
             Print num lines of leading and trailing context surrounding each
             match.  The default is 2 and is equivalent to -A 2 -B 2.  Note:
             no whitespace may be given between the option and its argument.

One gotcha here is that -A and -B have a space between the operand and its arguments, while -C does not.

And now, in practice, a few simple examples showing how it works relative to a standard grep:

% cat ./.zshrc| grep saveDot
function saveDot(){
% cat ./.zshrc| grep saveDot -C2

## Save a dot file
function saveDot(){
    echo "Updating $HOME/$1"
    cat ~/code/dotfiles/$1 > ~/$1
% cat ./.zshrc| grep saveDot -A3
function saveDot(){
    echo "Updating $HOME/$1"
    cat ~/code/dotfiles/$1 > ~/$1
}

Related Posts
  • 2021 Daily Journal


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!