Home > Net >  removing a line and the line before it
removing a line and the line before it

Time:01-15

i'm trying to remove the lines containing literal ,32, and the line BEFORE/ABOVE it that should always contain ,34,

files example:
dd,34,dd 10:00 game1
dd,32,dd 10:01 game1
dd,34,dd 12:30 game2
dd,31,dd 12:32 game2 
dd,34,dd 13:54 game3
dd,31,dd 13:55 game3
dd,34,dd 15:00 game1
dd,32,dd 15:00 game1

#note: there's a few thousand of these lines in the file

I've tried using grep grep -v -B1 ',32,'file1 > file2

file2 should be all lines from file1 except for the lines containing ,32, and the line before ,32, doesnt work as intented

sed "/\,32\,/, 1d" rp1 > rep2 sed "/\,32\,/,~1d" rp1 > rep2 deletes lines in a different order than intended. The amounts of lines containing ,34, match the lines containing the rest of the symbols. As if it deletes the ,32, line and the line AFTER instead of BEOFRE.

OUTPUT AFTER USING SED command from above:

dd,34,dd 10:00 game1
dd,31,dd 12:32 game2 
dd,34,dd 13:54 game3
dd,31,dd 13:55 game3
dd,34,dd 15:00 game1

DESIRED OUTPUT:

dd,34,dd 12:30 game2
dd,31,dd 12:32 game2 
dd,34,dd 13:54 game3
dd,31,dd 13:55 game3

CodePudding user response:

To get the desired output you need to understand The Concept of 'Hold space' and 'Pattern space' in sed
Please refer the above URL to get an understanding.

You can use the following sed command to get the desired output:

sed -n '/,32,/{s/.*//;x;d;};x;p;${x;p;}' inputFileName | sed '/^$/d'

The above command will delete all the lines matching ,32, pattern and the line exactly above/before it.

The above command is storing every line in a buffer called as hold space, when sed encounters the pattern which is ,32, it deletes the content of pattern space i.e. current line as well as hold space i.e. the previous line.

Hope this answers the question.

CodePudding user response:

Using any awk plus tac:

$ tac file | awk '/,32,/{c=2} !(c&&c--)' | tac
dd,34,dd 12:30 game2
dd,31,dd 12:32 game2
dd,34,dd 13:54 game3
dd,31,dd 13:55 game3

If you wanted to delete blocks of, say, 5 lines instead of blocks of 2 lines, you'd just change c=2 to c=5.

See Printing with sed or awk a line following a matching pattern for an explanation for that awk script and similar idioms.

CodePudding user response:

This might work for you (GNU sed):

sed -n 'N;/\n.*,32,/d;P;D' file

Open a two line window.

If the second line contains ,32,, delete both lines.

Otherwise, print/delete the first and re-establish the two line window.

  • Related