melatonin15
melatonin15

Reputation: 2269

Splitting text file based on column value in unix

I have a text file:

head train_test_split.txt 
1 0
2 1
3 0
4 1
5 1

What I want to do is save the first column values for which second column value is 1 to file train.txt.

So, the corresponding first column value for second column value with 1 are: 2,4,5. So, in my train.txt file i want:

2
4
5

How can I do this easily unix?

Upvotes: 0

Views: 1282

Answers (2)

dawg
dawg

Reputation: 103834

In Perl:

$ perl -lane 'print "$F[0]" if $F[1]==1' file

Or GNU grep:

$ grep -oP '^(\S+)(?=[ \t]+1$)' file

But awk is the best. Use awk...

Upvotes: 1

janos
janos

Reputation: 124646

You can use awk for this:

awk '$2 == 1 { print $1 }' inputfile

That is, $2 == 1 is a filter, matching lines where the 2nd column is 1, and print $1 means to print the first column.

Upvotes: 5

Related Questions