AWE
AWE

Reputation: 4135

Delete lines from file

I have a question similar to this one: Delete lines from file with SED or AWK

how can I delete rows that start with 3 and 5 and everything in between in this file:

ssadfsadfsdf
asdfsadf
asdfsadf
asdfsadf
asdfsdf
1 z z z lkj klj lkj
2 satan er kaerleikur lkj lkj lkj
3 z z z
4 asdflj asd sdf
5 z z z
6 asdf sdaf asdf
7 z z z lkj lkj lkj
8 sdf safd asdf
9 z z z

If the answer is clearly elsewhere I will delete this question.

what if it looked liked this:

asd        ssadfsadfsdf
asd        asdfsadf
asd        asdfsadf
asd        asdfsadf
asd        asdfsdf
asd        1 z z z lkj klj lkj
asd        2 satan er kaerleikur lkj lkj lkj
asd        3 z z z
asd        4 asdflj asd sdf
asd        5 z z z
asd        6 asdf sdaf asdf
asd        7 z z z lkj lkj lkj
asd        8 sdf safd asdf
asd        9 z z z

Upvotes: 1

Views: 506

Answers (4)

schot
schot

Reputation: 11278

You can use an awk range pattern to skip line matching pattern 1 up to pattern 2:

awk '$1 == 3, $1 == 5 { next }; { print }' INFILE

I do a numerical comparison on field $1 instead of a regular expression such as /^3/ because that would also match '30', '31', etc.

If the number is the second field of the line (as in your edited example input), just change $1 to $2. Let me know if this works for you.

Upvotes: 4

AzP
AzP

Reputation: 1101

A quick Google gave me this as seconds answer:

http://www.cyberciti.biz/faq/sed-howto-remove-lines-paragraphs/

$ sed '/WORD1/,/WORD2/d' input.txt > output.txt

To make sure it's matching "beginning of line" like you said, you can start the pattern with the ^ symbol.

If you're using Vim (which has sed built in) you can do a range command like:

:/^3.*/,/^5.*/ d

where d is the delete command, and :/exp1/,/exp2/ the range.

Upvotes: 3

Kent
Kent

Reputation: 195289

awk '$2!~/^[3|5]/' yourFile 

will do it for you.

see the test below:

kent$  echo "asd        ssadfsadfsdf
asd        asdfsadf
asd        asdfsadf
asd        asdfsadf
asd        asdfsdf
asd        1 z z z lkj klj lkj
asd        2 satan er kaerleikur lkj lkj lkj
asd        3 z z z
asd        4 asdflj asd sdf
asd        5 z z z
asd        6 asdf sdaf asdf
asd        7 z z z lkj lkj lkj
asd        8 sdf safd asdf
asd        9 z z z"|awk '$2!~/^[3|5]/'

output:

asd        ssadfsadfsdf
asd        asdfsadf
asd        asdfsadf
asd        asdfsadf
asd        asdfsdf
asd        1 z z z lkj klj lkj
asd        2 satan er kaerleikur lkj lkj lkj
asd        4 asdflj asd sdf
asd        6 asdf sdaf asdf
asd        7 z z z lkj lkj lkj
asd        8 sdf safd asdf
asd        9 z z z

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363858

awk '/^3/ {del=1}
     (del==0) {print}
     /^5/ {del=0}' FILE

Upvotes: 1

Related Questions