user3660245
user3660245

Reputation: 123

Replace repeating variables by "NA" using awk

Suppose I have the next file:

1 Blue
2 Red
3 Yellow
4 Yellow
5 Yellow
6 Purple
7 Purple
8 Green

And I would like to get the following file, replacing the repeated variables by "NA"

1 Blue
2 Red
3 Yellow
4 NA
5 NA
6 Purple
7 NA
8 Green

Upvotes: 0

Views: 149

Answers (3)

Ed Morton
Ed Morton

Reputation: 204310

$ awk '{print $1, ($2==p ? "NA" : $2); p=$2}' file
1 Blue
2 Red
3 Yellow
4 NA
5 NA
6 Purple
7 NA
8 Green

Upvotes: 1

Jingtao Ren
Jingtao Ren

Reputation: 24

awk '{ if ($2 == COLOR) {print $1, "NA"} else {COLOR=$2; print $1, $2 } }'

Upvotes: 0

VIPIN KUMAR
VIPIN KUMAR

Reputation: 3147

Try this -

$ awk 'a[$2]++{$2="NA"} 1' f
1 Blue
2 Red
3 Yellow
4 NA
5 NA
6 Purple
7 NA
8 Green

Upvotes: 5

Related Questions