venkyjack
venkyjack

Reputation: 33

How to use cut lines based on a pattern match?

I have a file with the output as below

--B32934--
descr:     X
descr:     Y
descr:     Z
--B20484
descr:     A
descr:     B
descr:     C
--B41946
descr:     1
descr:     2
descr:     3
descr:     4

I just need the --BXXXX number and the first line, the rest of the lines need to be stripped out from the file. Is it possible to delete the lines >1 based on the pattern match --B?

For example under "--B32934" i just want "descr:X". The rest of the lines need to be deleted.

Desired result should look like this

--B32934--
descr:     X

Upvotes: 1

Views: 1878

Answers (4)

Josef
Josef

Reputation: 232

Here's another solution with grep

grep -e '^--B[0-9]\+' --no-group-separator -A 1 file

outputs:

--B32934--
descr:     X
--B20484
descr:     A
--B41946
descr:     1

Upvotes: 0

potong
potong

Reputation: 58518

This might work for you (GNU sed):

sed '/^--B\S\+/!d;n' file

Delete any line that does not begin with --B followed by one or more non-space characters. Otherwise print that line and the following.

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

Two approaches:

-- awk approach:

awk '/^--B[0-9]+/{ r=NR; print }(NR-1)==r' file
  • /^--B[0-9]+/ - if the line starts with pattern

  • r=NR - hold the record number

  • (NR-1)==r - if it's the next line after the pattern line

To capture the following 2 lines after the pattern line - use this approach:

awk '/^--B[0-9]+/{ r=NR; print }(NR-1)==r || (NR-2)==r' file

-- GNU sed approach:

sed -n '/--B[0-9]*/{N;p;}' file
  • N - add a newline to the pattern space, then append the next line of input to the pattern space (GNU extension)

The output (for both approaches):

--B32934--
descr: X
--B20484
descr: A
--B41946
descr: 1

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158170

You may use the following awk command:

awk 'p{print;p=0}/^-/{print;p=1}' file

Explanation:

If the variable p is true, print the current line, set p back to 0 (false). If the line starts with a -, print the current line and set p to 1 (true) (in order to print the next line).

Upvotes: 2

Related Questions