Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'm a beginner in awk programming. This post is to clarify a doubt. I have file like this:

70 17 5 mb
71 18 6 ms
72 19 7 ml
73 20 8 mw

in which 4th column is a string. I want to make changes in the 3rd column with respect to 4th column. For example: to read the 4th column, if $4=ms then $3=$3+1.

Actually I don't know how to make the program read string ms.

Please help me regarding this!

share|improve this question
add comment

2 Answers

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 }'

share|improve this answer
add comment

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 string ms 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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.