Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Row After Counting Number of Columns In Text File

Tags:

linux

bash

unix

awk

I need to dynamically delete a line after counting the number of columns in it. For instance, if the number of columns in the line is less than X, delete the entire line. I have a text file that contains 100+ lines.

Here's what I have so far, which counts the total number of columns in each line of the text file...

Text Sample:

KGAI 2 2 40 50 50 98 75 10 35 40 15 25 15 55
KGED 3 3 15 25 20 60 60 20 50 25 15 25 20 40
KGFL 1 10 3 4 3 85 25
KGHG        15 20 40 20 20 20 20
KGKJ 20 80 25 20 25 97 50 20 60 45 30 30 25 30
KGNR 2 30 4 5 5 25 90 10 35 15 15 15 10 20
KGON 1 1 20 10 5 85 65 5 20 30 15 10 15 25
KGTB
KHEF 2 2 20 30 50 98 60 10 30 25 10 15 10 45

Code:

cat text_data | awk 'BEGIN{FS=" "};{print NF}'

Output:

15
15
8
8
15
15
15
1
15
like image 616
Aaron Perry Avatar asked Nov 26 '15 12:11

Aaron Perry


1 Answers

Do it the other way round: just print those that have at least X columns:

awk -v cols=5 'NF>=cols' file

That is, set the variable cols to the value of minimum amount of cols you want the line to have. Whenever it is true, the line will be printed.

In this case it returns:

KGAI 2 2 40 50 50 98 75 10 35 40 15 25 15 55
KGED 3 3 15 25 20 60 60 20 50 25 15 25 20 40
KGFL 1 10 3 4 3 85 25
KGHG        15 20 40 20 20 20 20
KGKJ 20 80 25 20 25 97 50 20 60 45 30 30 25 30
KGNR 2 30 4 5 5 25 90 10 35 15 15 15 10 20
KGON 1 1 20 10 5 85 65 5 20 30 15 10 15 25
KHEF 2 2 20 30 50 98 60 10 30 25 10 15 10 45
like image 84
fedorqui 'SO stop harming' Avatar answered Oct 15 '22 23:10

fedorqui 'SO stop harming'