简体   繁体   中英

Increment Number with AWK

I have a series of blocks of code with the following pattern:

<div class="label label-primary">#1</div>
<!--A1_START-->

  [code block]

<!--A1_END-->

The blocks are numbered 1-44. Block #6, however, has been removed and so I need the numeric value in blocks 7-44 decremented.

How can I use awk to modify the appropriate blocks? There are dozens of similar questions here on SO, but I can't seem to modify any of them to produce the desired result.

You can use "strange" field separators, so that the number lies alone and ready to be changed:

awk -v FS='<div class="label label-primary">#|</div>' '$2>7{sub($2, $2-1)}1' a

Explanation

  • -v FS='<div class="label label-primary">#|</div> set the field separator to either <div class="label label-primary"># or </div> . This way, the number will be the field 2 ( $2 ).
  • $2>7{sub($2, $2-1)} in case $2 is bigger than 7 , then replace it with itself minus 1.
  • 1 as it is evaluated as True, it performs the default awk action: print the current record (line).

Test

$ cat a
<div class="label label-primary">#1</div>
<!--A1_START-->

  [code block]

<!--A1_END-->

<div class="label label-primary">#2</div>
<!--A1_START-->

  [code block]

<!--A1_END-->

<div class="label label-primary">#10</div>
<!--A1_START-->

  [code block]

<!--A1_END-->

And let's run it:

$ awk -v FS='<div class="label label-primary">#|</div>' '$2>7{sub($2, $2-1)}1' a
<div class="label label-primary">#1</div>
<!--A1_START-->

  [code block]

<!--A1_END-->

<div class="label label-primary">#2</div>
<!--A1_START-->

  [code block]

<!--A1_END-->

<div class="label label-primary">#9</div>  # <--- 10 is now 9
<!--A1_START-->

  [code block]

<!--A1_END-->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM