0

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?

1
  • does your grep support -P (--perl-regexp) ? Commented May 13, 2017 at 20:19

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Or just the 'truthiness' of $2 will work: awk '$2{print $1}'
@dawg for the given sample yes, but it was not specified that the 2nd column will only have 0 and 1 values.
1

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...

1 Comment

the grep one can be simplified to grep -oP '^\S+(?=\h+1$)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.