0

I have blocks like

<block>
 6   3  0.3464400E-01  0.4497077E+03  0.7546771E-02  0.1037429E+00
       21   -1    0    0  501  502  0.00000000000E+00  0.00000000000E+00  0.27717368685E+03  0.27717368685E+03  0.00000000000E+00 0.  1.
 </block>

but also

<block>
 4   1  0.3464400E-01  0.3573334E+03  0.7546771E-02  0.1068535E+00
        6    1    1    2  501    0 -0.28596283579E+03 -0.12710688463E+03  0.60083326400E+02  0.36234949936E+03  0.17250000000E+03 0. -1. 
</block>

What I need, is to look only in the first line after the "block" and only if a "4 1" pattern is true, then replace the 4rth column with another number but all other lines should remain untouched. I found this How to replace the nth column/field in a comma-separated string using sed/awk? but was not very helpful in my case (my columns are space separated). Sorry in advance if this already a possible duplicate...

Community
  • 1
  • 1
Just_Newbie
  • 447
  • 1
  • 4
  • 11

2 Answers2

1

i think you want to change this:

<block>
 4   1  0.3464400E-01  0.3573334E+03

to this:

<block>
 4   1  0.3464400E-01  <something else>

awk is a good tool for this. here is a way to do it:

awk '{
  if($1 == "<block>"){
    block_row=NR
  }
  else if(block_row>0 && NR == block_row+1 && $1 == 4 && $2 == 1){
    $4 = "<something>"
  }
  print $0
}' infile > outfile

mv -f outfile infile
webb
  • 4,180
  • 1
  • 17
  • 26
1

Assuming you have a value available to replace, you can do this simply with awk

awk '/<block>/ { getline;  if (($1=="4") && ($2=="1")) {$4=<value>;print} }' file
#                                                           ^Value to be replaced

In the above expression replace the <value> with the value you need. The logic is quite straight-forward. Search for the pattern, get the line next to it, check if the the first and second column values are 4 and 1 as expected and replace the value of column 4.

Assuming you have a file like below:-

$ cat file

<block>
4   1  0.3464400E-01  0.3573334E+03  0.7546771E-02  0.1068535E+00
6    1    1    2  501    0 -0.28596283579E+03 -0.12710688463E+03  0.60083326400E+02  0.36234949936E+03  0.17250000000E+03 0. -1.
</block>
<block>
4   2  0.3464400E-01  0.3573334E+03  0.7546771E-02  0.1068535E+00
6    1    1    2  501    0 -0.28596283579E+03 -0.12710688463E+03  0.60083326400E+02  0.36234949936E+03  0.17250000000E+03 0. -1.
</block>

Am running the command with replacement value as 0,

$ awk '/<block>/ { getline;  if (($1=="4") && ($2=="1")) {$4=0;print} }' file
4 1 0.3464400E-01 0 0.7546771E-02 0.1068535E+00
Inian
  • 80,270
  • 14
  • 142
  • 161