user1606106
user1606106

Reputation: 207

How to delete all the lines which have blank fields with sed or awk?

I would like to delete all the lines which have blank fields from text files. How can I change the following code to make the changes directly to the files?

awk '!/^\t|\t\t|\t$/' *.txt    

AD  125.9    MN 124.9
AC  38.9     VG 13.2
AV  34.6     BG 33.0
GL  126.2   
CY  34.9    
CY  44.9    

desired output

AD  125.9    MN 124.9
AC  38.9     VG 13.2
AV  34.6     BG 33.0

Upvotes: 1

Views: 3878

Answers (5)

Steve
Steve

Reputation: 54402

One way using GNU sed:

sed -n -s -i '/[^ \t]* [^ \t]* [^ \t]* [^ \t]/p' *.txt

Results:

AD  125.9    MN 124.9
AC  38.9     VG 13.2
AV  34.6     BG 33.0

Upvotes: 3

Vijay
Vijay

Reputation: 67231

assuming your file has a max of 4 fields:

awk '{for(i=1;i<5;i++){if($i=="")next;}print}' file_name

tested below:

> cat temp
AD      125.9    MN     124.9
AC      38.9     VG     13.2
AV      34.6     BG     33.0
GL      126.2
CY      34.9
CY      44.9
>awk '{for(i=1;i<5;i++){if($i=="")next;}print}' temp
AD      125.9    MN     124.9
AC      38.9     VG     13.2
AV      34.6     BG     33.0
>

Upvotes: 0

Kent
Kent

Reputation: 195079

alternative awk one-liner:

awk 'NF==4' yourFile

Upvotes: 7

Zsolt Botykai
Zsolt Botykai

Reputation: 51613

Using your input this might work (but it depends if there are spaces or tabs):

sed '/^.\{13\}\s/d' INPUTFILE

Or this:

awk 'substr($0,14,1) = " " { print }' INPUTFILE

Upvotes: 0

beny23
beny23

Reputation: 35018

You could use a for loop with your original awk command:

for f in *.txt
do
  cp $f /tmp/mytempfile
  awk '!/^\t|\t\t|\t$/' /tmp/mytempfile > $f
done

Upvotes: 0

Related Questions