Splitting file using awk

I have file with below content

FG1620000|20000
FG1623000|23000
FG1625000|25000
FG1643894|43894
FG1643895|43895
FG1643896|43896
FG1643897|43897
FG1643898|43898

My aim is to split the above file into two files based on the value in the second field.
If the value in second field is <=30000, the field one should written into a separate file "high.txt"

"high.txt"

FG1643894|43894
FG1643895|43895
FG1643896|43896
FG1643897|43897
FG1643898|43898

"low.txt"

FG1620000|20000
FG1623000|23000
FG1625000|25000

My code is

cat file| awk -F'|' '{ if ($1 <= "20000") {print $1 >> "high.txt"} else {print $1 >> "low.txt"} }'

but the entire content of the file gets printed to "low.txt"

Where am I going wrong?

That's useless use of cat.

And you are comparing $1, you should compare $2:)

try this..

awk -F'|' '{ if ($2 >= 30000) {print  >> "high.txt"} else {print  >> "low.txt"} }' file

Beware, some awk implementations will produce unexpected results with an expression such as $2 <= "20000" . Although the comparison is intended to be a numeric one, some awks (gawk included) will treat that as string comparison and return true if $2 is (say) 100000.

gawk 'BEGIN{a=100000;if(a<="20000") print "string comparison"}'
string comparison

It's better to force numeric comparison and/or drop the quotes:

a<=20000

or

a+0<=20000+0
1 Like