user10657934
user10657934

Reputation: 157

filtering data in a text file using awk

I am trying to filter rows based on one column in a big text file. here is a small example:

example:

-3261   1
777 1
-45574  1
1017    1
-2802   1
969 1
1800    1
-128768 1
-7614   1
-136751 1
-64104  1
134844  1

I want to filter based on the first column. if the numbers in the 1st column are smaller than 4000 or larger than -4000 keep the row and filter out the rest. here is the expected output:

expected output:

-3261   1
777 1
1017    1
-2802   1
969 1
1800    1

I am using awk using this code:

awk -F "\t" '{ if($1 >= -4000 || $1 <= 4000) { print } }' infile.txt > outfile.txt

using this code output is the same as input file. do you know how to fix it?

Upvotes: 1

Views: 820

Answers (3)

karakfa
karakfa

Reputation: 67467

another way to write this

$ awk '$1^2 <= 4000^2' input_file

Upvotes: 2

Kent
Kent

Reputation: 195039

first of all, you should know that

smaller than 4000 or larger than -4000

and

smaller than 4000 AND larger than -4000

are different.

-80000 is valid for the OR condition, however not for the 2nd. I hope you meant the right thing. For your requirement, (the OR one), you can do (following your "or" requirement ):

awk '$1>=-4000 || $1<=4000'   file

Note, this will first check >=-4000, that is, a row with value 99999999 will be valid, in output.

If you meant the AND condition, you need:

awk '$1<4000 && $1>-4000' file

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133428

Could you please try following.

awk '$1<4000 && $1>-4000'   Input_file

Where is your code going wrong, you need to put && condition since you want to check both conditions to be TRUE. || conditions will print those elements also where anyone of the conditions is TRUE too.

More information on && and || operators from man awk page:

   The &&, ||, and !  operators are logical AND, logical OR, and logical NOT, respectively, as in C.  They do short-circuit evaluation,

also as in C, and are used for combining more primitive pattern expressions. As in most languages, parentheses may be used to change the order of evalua- tion.

Upvotes: 1

Related Questions