chimeric
chimeric

Reputation: 895

Awk replace not working in "if" statement

I'm trying to replace a specific column in a file, let's say the third column in test.txt.

Create test.txt:

echo "1 2 -1" > test.txt
echo "3 4 +1" >> test.txt

If I do a simple replace, it works:

awk '$3="cows"' test.txt

1 2 cows
3 4 cows

However, if I use a conditional to vary the output, I get nothing:

awk '{
if ($3 == "+1")
     $3="cows";
else if ($3 == "-1")
     $3="sheep";
}' test.txt

What am I missing here? Thanks!

Upvotes: 2

Views: 69

Answers (2)

chimeric
chimeric

Reputation: 895

You guys are right, here's the correct formatting.

    awk '{
    if ($3 == "+1")
         $3="cows";
    else if ($3 == "-1")
         $3="sheep";
    print
    }' test.txt

Upvotes: 0

Roland Illig
Roland Illig

Reputation: 41625

Awk programs are composed of conditions and actions, in the form condition { action }.

Awk has a default action, which is to print the current line.

In your first program the assignment is a condition, not an action, since there are no curly braces. Therefore the default action is executed.

In your second program, you have defined an action, which replaces the default action. Therefore, the print is not executed anymore, and you have to do it yourself.

Upvotes: 2

Related Questions