adeluccar
adeluccar

Reputation: 152

How to Find & Replace Strings with Incrementing Variables in a Text File Using Awk

Problem

How can I use awk to:

  1. Find a string
  2. Add an integer to that string
  3. Increment the integer
  4. Rinse and Repeat until EOF

Input File

Foo Figure
![Figure. Foo](images/foo.png)

Bar Figure
![Figure. "Bar"](images/bar.png)

Output File

Foo Figure
![Figure 1. Foo](images/foo.png)

Bar Figure
![Figure 2. "Bar"](images/bar.png)

Upvotes: 1

Views: 78

Answers (2)

Ed Morton
Ed Morton

Reputation: 204731

$ awk 'sub(/!\[Figure/,"& "i+1){i++} 1' file
Foo Figure
![Figure 1. Foo](images/foo.png)

Bar Figure
![Figure 2. "Bar"](images/bar.png)

Upvotes: 4

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5318

awk '/Figure\./{gsub(/Figure/, "Figure " ++i)}1' File

Output:

Foo
![Figure 1. Foo](images/foo.png)

Bar
![Figure 2. "Bar"](images/bar.png)

Upvotes: 1

Related Questions