awk programming - Changing a field value conditionally
To do that, you need to use conditional statement inside action block {}
.
The syntax is if ( expr ) statement
So to match the condition where the 4th column is ms
and then reassign the value for the 3rd column when the condition is matched:
if ($4 == "ms") $3=$3+1
and then print the whole line using print $0
So the full command looks like this:
awk '{ if ($4 == "ms") $3=$3+1; print $0 }'
If the condition is simple you can use pattern matching to modify lines.
Assuming test.txt
contains the example data:
cat test.txt
70 17 5 mb
71 18 6 ms
72 19 7 ml
73 20 8 mw
Let's examine the following line and its output:
awk '/ms$/ {$3++} {print}' test.txt
70 17 5 mb
71 18 7 ms
72 19 7 ml
73 20 8 mw
The awk command reads the contents of test.txt
and runs the awk script /ms$/ {$3++} {print}
on each line. The script can be rewritten as:
/ms$/ {$3++}
{print}
- There are two actions in the script inside curly braces:
{}
.- The second is easier to explain: it just prints out the whole line.
- The first one contains a pattern specification before the action. The action will only run on matching lines. The pattern is written inside slashes:
//
.-
ms$
means each line having the stringms
at the end of line$
(The dollar sign indicates that the string should be the last on the line). - The action
$3++
increments the value of the third column by one.
-
Please note the {print}
action will always run, because there is no pattern for this action, but the {$3++}
pattern will only run if the string "ms" is found at the end of line. Also the incrementing happens before the print, so all necessary modifications will be performed on time.