Geparada
Geparada

Reputation: 3038

How to split a file based on a matching condition of a column?

I know that by using:

awk '($18 ~ 0)' file > match

I get all the lines that have a 0 on 18th field. Thus I tried to implement the same logic to split a file based on wether its 18th field has an "0" or not:

awk -F, '{ if ($18 ~ 0) print > "match"; else print > "not_match"}' file

But is not working, no line is printed on "match".

What am I doing wrong? Do you know other way to do this in bash?

Thanks for your time!

Upvotes: 0

Views: 294

Answers (1)

MattH
MattH

Reputation: 38247

Here's a minimal complete example of splitting the lines of a file conditionally based on field values:

[me@host]$ cat > /tmp/blah
0 Yes
1 No
1 No
0 Yes
1 No
[me@host]$ awk '($1 ~ 0) { print > "/tmp/match"; next } { print > "/tmp/non_match" }' /tmp/blah
[me@host]$ cat /tmp/match
0 Yes
0 Yes
[me@host]$ cat /tmp/non_match
1 No
1 No
1 No

Upvotes: 1

Related Questions