How to find/replace and increment a matched number with sed/awk?

后端 未结 4 957
情书的邮戳
情书的邮戳 2020-11-30 01:53

Straight to the point, I\'m wondering how to use grep/find/sed/awk to match a certain string (that ends with a number) and increment that number by 1. The closest I\'ve come

4条回答
  •  孤街浪徒
    2020-11-30 02:13

    Pure sed version:

    This version has no dependencies on other commands or environment variables. It uses explicit carrying. For carry I use the @ symbol, but another name can be used if you like. Use something that is not present in your input file. First it finds SEARCHSTRING and appends a @ to it. It repeats incrementing digits that have a pending carry (that is, have a carry symbol after it: [0-9]@) If 9 was incremented, this increment yields a carry itself, and the process will repeat until there are no more pending carries. Finally, carries that were yielded but not added to a digit yet are replaced by 1.

    sed "s/SEARCHSTRING[0-9]*[0-9]/&@/g;:a {s/0@/1/g;s/1@/2/g;s/2@/3/g;s/3@/4/g;s/4@/5/g;s/5@/6/g;s/6@/7/g;s/7@/8/g;s/8@/9/g;s/9@/@0/g;t a};s/@/1/g" numbers.txt
    

提交回复
热议问题