0

With grep filter a file, from that filtered lines do a math operation on a specific column, only in the lines that contains a string "value=", return all the lines from the first grep filter and the lines where the math operation was done.

Example:

Use grep to filter lines that contains the string "update", this is easy, I got it.

output:

...
col1 col2 update  col4  col5
col1 col2 update  value= 320
col1 col2 update  col4  col5
col1 col2 update  value= 210
...

Now I need to select only the lines that contains the string "value=" and multiply the next column by 25, but still get lines that doesn't have the value= string

output:

...
col1 col2 update  col4  col5
col1 col2 update  value= 8000
col1 col2 update  col4  col5
col1 col2 update  value= 5250
...

I have tried using an if statement and awk, but only returns the lines where the math operation was done.

2
  • Can you show us what commands you're using to get these segments of output? You might be almost there...
    – roaima
    Nov 1, 2019 at 18:55
  • 1
    You don't need grep when you're using awk.
    – Ed Morton
    Nov 3, 2019 at 22:36

2 Answers 2

2

To execute math operations you must use awk or higher (sed and grep can not do math operations).

Replacing the grep in awk is quite simple, just use a regex /update/:

awk '/update/ { if ($4=="value=") { $5*=25 }; print }' ./file
2
  • You might want to use $3=="update" instead of just /update/ to make the filter more robust against arbitrary content on other columns (the OPs example would seem to indicate that in this particular case that would not happen, but the OPs question sounds a little like a homework assignment and it may be helpful for others whe are looking for a "real-world" application of this ...).
    – AdminBee
    Sep 25, 2020 at 8:17
  • @AdminBee Well, yes, that is quite more restrictive. It reads as "match lines of which the third column is exactly equal to update. That will produce much less "false positives" , but, for sure it may also produce more "false negatives". That is entirely dependent on what is meant to be matched. For that we only have what the OP wrote: "filter lines that contains the string update" (note the word lines, not fields). You are infering from the example data that that only apply to the third field, but that has not been said. We should not assume, the OP should clarify.
    – done
    Sep 25, 2020 at 16:06
0

I got this:

awk '$4=="value=" {$5=($5*25)}1' foo
1
  • Thanks it works, so the comand will only do the operation if in the fourth column the string "value=" is present? I understand this right?
    – Tapioca
    Nov 1, 2019 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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