Alex Collins
Alex Collins

Reputation: 1016

In bash, how do a replace a string in a file with a dynamic replacement

Specifically, I have a Markdown document with figures listed as so

```
![Figure XXX](images/figure-of-a-thing.png)
...
![Figure XXX](images/figure-of-another-thing.png)
```

I'd like to end up with the following:

```
![Figure 1](images/figure-of-a-thing.png)
...
![Figure 2](images/figure-of-another-thing.png)
```

I.e., with a monotonically increasing number. It strikes me that there are some sed/awk ninjas out there who can solve this.

Upvotes: 0

Views: 75

Answers (1)

Wintermute
Wintermute

Reputation: 44063

I'd say

awk '/^!\[Figure/ { sub(/XXX/, ++n) } 1' filename.md

This will replace the first occurrence of XXX in all lines that begin with ![Figure with a running counter.

If the ![Figure sequences can also appear in the middle of a line and possibly several times in one line (I don't think this is probable, but for the sake of completeness, let's consider the case), you might use

awk 'BEGIN { n = 1 } { while(sub(/!\[Figure XXX/, "![Figure " n)) ++n; } 1' filename.md

Upvotes: 2

Related Questions