如何找到&使用Awk替换文本文件中增量变量的字符串

时间:2016-11-18 04:42:32

标签: shell awk command-line-interface

问题

我如何使用awk:

  1. 查找字符串
  2. 为该字符串添加整数
  3. 递增整数
  4. 冲洗并重复直至EOF
  5. 输入文件

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

    输出文件

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

2 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:1)

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

输出:

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

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