Michael Apostolides
Michael Apostolides

Reputation: 31

awk substitute column value if not equal to either of 2 values

I am working with a TAB separated file, as follows:

+    +    +
-    +    .
+    +    -
+    +    &
+    -    )

I want to replace column $3 with "NA", but only if it is not equal to either "+" or "-".

The file should be changed to look as follows:

+    +    +
-    +    NA
+    +    -
+    +    NA
+    -    NA

I have tried the following, but it does not work.

cat $file |  awk 'FS=OFS="\t"{ if ($3 !="+" && $3 != "-" ); print }' 

How can I do the above?

Upvotes: 2

Views: 509

Answers (2)

anubhava
anubhava

Reputation: 785146

You are close. You may use:

awk 'BEGIN{FS=OFS="\t"} $3 !~ /^[-+]$/{$3="NA"} 1' file
+   +   +
-   +   NA
+   +   -
+   +   NA
+   -   NA

Upvotes: 2

karakfa
karakfa

Reputation: 67497

with sed it's easier...

$ sed -E 's/[^+-]$/NA/' file

+    +    +
-    +    NA
+    +    -
+    +    NA
+    -    NA

Upvotes: 1

Related Questions