Ubuntu – How to use the grep command to extract line which is the next line of greping line

grep

I have text file like (the specific part of the whole file);

!        lat             long          elev (m)
!      44.5199005      11.6468000       50.4276

I need to extract second line and save them in another text file. The numbers are variable and "!" syntax is also exist several times in the text. For the first line there is always 8 spaces between "!" and "lat" but this is not the case for the second line. Is there any command available to allow me to extract next line after grep "! lat" text

Best Answer

You can use grep -A1 'expression'

From the manual:

-A num
--after-context=num
    Print num lines of trailing context after matching lines.

In your case:

grep -A1 "!        lat" foo | grep -v "!        lat"

should work to extract the second line only.

Note:
You can use grep -P '^! {8}lat' instead of typing many . This is less error prone. The -P flag enables perl style regular expressions and {8} (There is a space before the '{') matches exactly 8 spaces.

Related Question