if pattern found in column add specific value to next column in bash

I have a file with 2 columns and I would like that, if a specific value is found in the second column, a "1" will be added to the third column. If the pattern is not found, a "0" should be added to the third column. If tried the following code but it is not working...

if grep -F "PATTERN" myfile.txt; then
        awk '{print $1, $2, $3 == 1}'
else
        awk '{print $1, $2, $3 == 0}’
fi

My input looks like this:

ID1    Pop1
ID2    Pop1
ID3    PATTERN

And my desired output would be:

ID1    Pop1    0
ID2    Pop1    0
ID3    PATTERN    1

Upvotes: 1

Views: 1064

Answers (3)

Ed Morton
Ed Morton

Reputation: 203129

wrt $3 == 1 in your script where I assume you were trying to assign the value 1 to $3 - like in many languages, == is for comparison, = is for assignment.

$ awk '{print $0, ($2=="PATTERN")}' file
ID1    Pop1 0
ID2    Pop1 0
ID3    PATTERN 1

or if you like golf:

$ awk '{$3=($2=="PATTERN")}1' file
ID1 Pop1 0
ID2 Pop1 0
ID3 PATTERN 1

Upvotes: 2

Jotne
Jotne

Reputation: 41446

An short awk version

awk '$2~/PATTERN/?$0=$0FS 1:$0=$0FS 0' file
ID1    Pop1 0
ID2    Pop1 0
ID3    PATTERN 1

If PATTERN found add 1, else add 0. Default action is print.

$2~/PATTERN/ ?$0=$0FS 1 :$0=$0FS 0
---Test----- --True?--- --False?--

Upvotes: 1

j23
j23

Reputation: 3530

This will match for a string containing PATTERN and add 1 or 0 as last column. FS is file seperator. You can use " " or tab as you desire.

awk '{if ( $2 ~ /PATTERN/ ) {print $0 FS "1"} else {print $0 FS "0"}}' file

Upvotes: 2

Related Questions