Using sed to replace numbers

I would like to replace some of the numbers in the file with the result of the calculation using the found number and how to use sed on MacOSX. I have tried many options, and now I know that I need to use -E to use a modern, not a basic regular expression.

Some examples:

echo "bla 18934750 + wwv_flow_id.offset bla" | sed s/\ +\ wwv_flow_id.offset/blabla/ 

gives

 bla 18934750blabla bla 

Thus, without -E, it finds and replaces the fixed text. But with -E this does not:

 echo "bla 18934750 + wwv_flow_id.offset bla" | sed -E s/\ +\ wwv_flow_id.offset/blabla/ 

gives

 bla 18934750 + wwv_flow_id.offset bla 

In other words: no matching and no text changes. The ultimate goal is to find the number that precedes the fixed text "+ wwv_flow_id.offset", and use that number and subtract the fixed number from it (say 750), so the final result will look like this:

 bla 18934000 + wwv_flow_id.offset bla 

And for this I need at least backlinks, which also do not work as I expected, because

 echo "bla 18934750 + wwv_flow_id.offset bla" | sed -E s/\([0-9]+\)\ /\1/ 

gives

 bla 1+ wwv_flow_id.offset bla 

I hope some regular expression guru can help me here.


UPDATE

With ruach, this is what I have now:

 echo "bla 18934750 + wwv_flow_id.offset bla" | sed -E 's/([0-9]+) \+ wwv_flow_id.offset/(\1-750) \+ wwv_flow_id.offset/' 

which returns:

 bla (18934750-750) + wwv_flow_id.offset bla 

Now the bonus question: how to turn it into

 bla 18934000 + wwv_flow_id.offset bla 




UPDATE 2

I managed to achieve the desired result by combining sed with awk, for example:

 echo "bla 18934750 + wwv_flow_id.offset bla" | sed -E 's/([0-9]+)([ ]*)\+([ ]*)wwv_flow_id.offset/~\1~\2\+\3wwv_flow_id.offset/' | awk -F~ '{print $1 $2-750 $3}' 

(I know for sure that there are no tokens in the source string ~ )

+4
source share
1 answer

In "modern" regular expressions, + has a special meaning - it means "one or more" (just like * means "zero or more") - therefore, to match the actual plus sign, you need to use \+ . Since you apparently prefer not to enclose the sed - script in quotation marks, you should write it as \\+ :

 echo "bla 18934750 + wwv_flow_id.offset bla" | sed -E s/\ \\+\ wwv_flow_id.offset/blabla/ 

although I think it will make your life easier if you give up this preference and write:

 echo "bla 18934750 + wwv_flow_id.offset bla" | sed -E 's/ \+ wwv_flow_id.offset/blabla/' 

In the quote of your argument, the problem with a backlink will also be considered, in which Bash translates \1 to 1 :

 echo "bla 18934750 + wwv_flow_id.offset bla" | sed -E 's/([0-9]+) /\1/' 

although if you prefer to stick with the non-quoted- sed -script style, you can write \\1 :

 echo "bla 18934750 + wwv_flow_id.offset bla" | sed -E s/\([0-9]+\)\ /\\1/ 
+8
source

Source: https://habr.com/ru/post/1437041/


All Articles