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

后端 未结 4 953
情书的邮戳
情书的邮戳 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:11

    I think finding file isn't the difficult part for you. I therefore just go to the point, to do the +1 calculation. If you have gnu sed, it could be done in this way:

    sed -r 's/(.*)(\?cache_version=)([0-9]+)(.*)/echo "\1\2$((\3+1))\4"/ge' file
    

    let's take an example:

    kent$  cat test 
    ello
    barbaz?cache_version=3fooooo
    bye
    
    kent$  sed -r 's/(.*)(\?cache_version=)([0-9]+)(.*)/echo "\1\2$((\3+1))\4"/ge' test     
    ello                                                                             
    barbaz?cache_version=4fooooo
    bye
    

    you could add -i option if you like.

    edit

    /e allows you to pass matched part to external command, and do substitution with the execution result. Gnu sed only.

    see this example: external command/tool echo, bc are used

    kent$  echo "result:3*3"|sed -r 's/(result:)(.*)/echo \1$(echo "\2"\|bc)/ge'       
    

    gives output:

    result:9
    

    you could use other powerful external command, like cut, sed (again), awk...

提交回复
热议问题