user741196
user741196

Reputation: 59

Modify the contents of a text file after a pattern has been found using sed/awk commands

I tried to come up with a Tcl script, but I'm looking for something in sed/awk commands to make this faster.

The file contains the following:

*Other text*
.....
.....
.....
SECTION LABELS {
lab M1 0 0 0 0 3 1 bot
lab M2 0 0 0 0 3 1 top
} SECTION LABELS

*Other text*
......
......
......
SECTION LABELS {
lab M1:NET 5207 12261 5207 12261 0 2 A
lab M2:NET 6880 5370 6880 5370 0 2 B
lab M1:NET 3454 5386 3454 5386 0 2 alpha
lab M2:NET 3454 5386 3454 5386 0 2 beta
} SECTION LABELS

I'm interested only in the lines containing within "SECTION LABELS". I'd like to:

So the output looks like:

*Other text*
.....
.....
.....
SECTION LABELS {
lab M1 0 0 0 0 3 1 bot
lab M2 0 0 0 0 3 1 top
} SECTION LABELS

*Other text*
......
......
......
SECTION LABELS {
lab M1 5207 12261 5207 12261 0 3 A
lab M2 6880 5370 6880 5370 0 3 B
lab M1 3454 5386 3454 5386 0 6 alpha
lab M2 3454 5386 3454 5386 0 6 beta
} SECTION LABELS

Upvotes: 0

Views: 104

Answers (2)

Jotne
Jotne

Reputation: 41460

Here is some to get you started:

awk '/SECTION LABELS/ {f=!f} f && /NET/ && !/lab M1(:NET)* 0 0 0 0/ {split($2,a,":");$2=a[1];if ($NF~/\<[A|B]\>/) $(NF-1)=3; else $(NF-1)=6}1' t
*Other text*
.....
.....
.....
SECTION LABELS {
lab M1 0 0 0 0 3 1 bot
lab M2 0 0 0 0 3 1 top
} SECTION LABELS

*Other text*
......
......
......
SECTION LABELS {
lab M1 5207 12261 5207 12261 0 3 A
lab M2 6880 5370 6880 5370 0 3 B
lab M1 3454 5386 3454 5386 0 6 alpha
lab M2 3454 5386 3454 5386 0 6 beta
} SECTION LABELS

Upvotes: 2

lihao
lihao

Reputation: 781

You can use the range as the pattern and then do operation on texts in between (inclusive). for your input:

awk '/^SECTION LABELS {/,/} SECTION LABELS/{
    sub(":NET","")
    if ($8 && !/M1 0 0 0 0/) $8 = ($NF ~ /^[AB]$/) ? 3 : 6 
}1' file.txt

Note: (1) you will need to adjust the 'if' section if there are more than 7 words in 'SECTION LABELS' (I supposed this is just a sample). you can change '$8' to '$9' or $9 != "" etc to skip the header and trailer.

(2) If A, B are string instead of chars, you will need to change the regex from ^[AB]$ to ^(A|B)$

(3) If you also want to keep M2 0 0 0 0 as is, then change !/M1 0 0 0 0/ to !/\<0 0 0 0\>/ where '\<' and '\>' are word boundaries in regex.

Upvotes: 2

Related Questions