vehomzzz
vehomzzz

Reputation: 44598

how to remove all lines containg less than n number of items

I want to remove all lines containing less than n number of items, space separated.

Say I want to remove lines containing less than 3 items. So the file below:

sdf sdfsdf sdfgsdf sdfsdfsd
sdf sdfsdf 
sdf sdfsdf sdfgsdf 
sdf sdfsdf sdfgsdf  ertert

Should result in:

sdf sdfsdf sdfgsdf sdfsdfsd
sdf sdfsdf sdfgsdf 
sdf sdfsdf sdfgsdf  ertert

Actually both awk and sed solutions are acceptable.

Upvotes: 2

Views: 3064

Answers (6)

Ethan Brown
Ethan Brown

Reputation: 703

I know you asked for a vi solution, but this is so dead simple in perl:

ethan@rover:~$ perl -ne 'print if split > 3' foo

where "foo" is your file.

Upvotes: 2

Raimondi
Raimondi

Reputation: 5303

Since there is a vim tag:

:v/\(\S\+\s\)\{2,}\S/d

Replace 2 with n-1.

Upvotes: 2

intuited
intuited

Reputation: 24054

In vim:

:v/\(\S\+\s\+\)\{3,}/d

Another option is

:g/./exec len(split(getline('.'))) < 3 ? 'd' : ''

You could also do something interesting like

:py vim.current.buffer[:] = [l for l in vim.current.buffer if len(l.split()) >= 3]

Upvotes: 4

zindel
zindel

Reputation: 1865

~$ cat test.txt | awk '{if(length($3) > 0) print $0;}'

Hope this helps

Upvotes: 1

siddardha
siddardha

Reputation: 200

NF is the number of fields in the record. Replace 2 with number you want

awk '{if (NF > 2) print $0}' inputFile.txt

Upvotes: 1

MJB
MJB

Reputation: 7686

How about this:

awk 'NF >= 3' filename

Upvotes: 12

Related Questions