【问题标题】:awk string search and replace with appended incremented numberawk 字符串搜索并替换为附加增量号
【发布时间】:2016-02-08 21:27:43
【问题描述】:

我在查找字符串(主题链接)然后使用 awk 附加一个递增的数字时遇到了一些问题。

我有以下全是一行的 html 文件:

<a class="topic-link" href="test.com/topic/gastrointestinal">Gastrointestinal</a>, <a class="topic-link" href="test.com/topic/nutrition">Nutrition</a>, <a class="topic-link" href="test.com/topic/weight-gain">Weight Gain</a> </p>

使用 awk 我试图获得:

<a class="topic-link1" href="test.com/topic/gastrointestinal">Gastrointestinal</a>, <a class="topic-link2" href="test.com/topic/nutrition">Nutrition</a>, <a class="topic-link3" href="test.com/topic/weight-gain">Weight Gain</a> </p>

我正在运行以下命令:

awk '{gsub("topic-link","topic-link"++i)}1' input file > output file

问题是结果会如下:

<a class="topic-link1" href="test.com/topic/gastrointestinal">Gastrointestinal</a>, <a class="topic-link1" href="test.com/topic/nutrition">Nutrition</a>, <a class="topic-link1" href="test.com/topic/weight-gain">Weight Gain</a> </p>

我想出的解决方案只有在“主题链接”的实例位于不同的行时才能正常工作,因此我被卡住了。

请告诉我,我在这里遗漏了一些非常明显的东西,或者如果您对替代方法有任何建议。

谢谢!

瑞兰

【问题讨论】:

    标签: linux awk gsub


    【解决方案1】:

    你的 gsub() 只被调用一次,所以 i 只增加一次。你需要一个循环:

    $ awk '{i=0; while(sub(/topic-link"/,"topic-link"++i"\""));} 1' file
    <a class="topic-link1" href="test.com/topic/gastrointestinal">Gastrointestinal</a>, <a class="topic-link2" href="test.com/topic/nutrition">Nutrition</a>, <a class="topic-link3" href="test.com/topic/weight-gain">Weight Gain</a> </p>
    

    【讨论】:

    • 感谢 Ed 这成功了。我想我需要一个循环,但不知道使用 awk 执行此操作的正确语法/过程。我会说我需要重温我的 google / stackoverflow 搜索 fu 前进。
    • 不客气。我建议您将问题多留几个小时,看看您是否得到您喜欢的答案,然后单击您认为最能解决您的问题的答案旁边的复选标记以关闭问题。另外 - 学习如何操作文本的最佳方法是阅读 Arnold Robbins 的《Effective Awk Programming, 4th Edition》一书。
    猜你喜欢
    • 1970-01-01
    • 2014-06-16
    • 2020-01-06
    • 2017-02-25
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    相关资源
    最近更新 更多