简体   繁体   中英

Is there any way that i can increment some number in sed after pattern matching

Is there any way that i can increment some number in sed after pattern matching

suppose i have this file

201 AD BBH NN
376 AD HGH JU

I want to match the starting integers and then add the number 5 to it in sed

Is this possible

You're probably better off using a slightly more advanced tool, such as awk :

pax$ cat qq.in
201 AD BBH NN
376 AD HGH JU

pax$ awk '{ print $0 " " $1+5 }' qq.in
201 AD BBH NN 206
376 AD HGH JU 381

If you really must do it in sed then, yes, it can be done. But it's butt-ugly. See here for a way of doing it:

#!/usr/bin/sed -f
/[^0-9]/ d
# replace all leading 9s by _ (any other character except digits, could
# be used)
:d
s/9\(_*\)$/_\1/
td

# incr last digit only.  The first line adds a most-significant
# digit of 1 if we have to add a digit.
#
# The tn commands are not necessary, but make the thing
# faster

s/^\(_*\)$/1\1/; tn
s/8\(_*\)$/9\1/; tn
s/7\(_*\)$/8\1/; tn
s/6\(_*\)$/7\1/; tn
s/5\(_*\)$/6\1/; tn
s/4\(_*\)$/5\1/; tn
s/3\(_*\)$/4\1/; tn
s/2\(_*\)$/3\1/; tn
s/1\(_*\)$/2\1/; tn
s/0\(_*\)$/1\1/; tn

:n
y/_/0/

This particular script adds 1 to a number and you can now (hopefully) understand why I called it butt-ugly. Trying to do this with sed is akin to trying to cut down a Karri tree with a goldfish.

You should use the right tool for the job.

使用awk,您可以尝试

cat fileName | awk '{num = 0; if ($1 ~ /[0-9][0-9][0-9]/) num = $1 + 5; print num $1 $2 $3;}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM