Sed - Replace the nearest next line / word after a specific pattern

I am new to shell scripts and any help is much appreciated.

I have a template like this rmd_ver=1.0.10

I want to find a pattern rmd_ver=and replace the numerical part 1.0.10with a new value in all matches. Hope my question is clear.

+4
source share
4 answers

To replace any value to the end of the line:

sed -i 's/\(rmd_ver=\)\(.*\)/\1R/' file
  • sed -i 's/p/r/' filereplace pwith rinfile
  • \( start the first group
  • rmd_ver= search pattern
  • \) end of the first group
  • \( start the second group
  • .* any characters
  • \) end of the second group
  • \1 back link to the first group
  • r replacement text

, , :

sed -i 's/\(rmd_ver=\)\(1\.0\.10\)/\1R/g' file
  • \. . .
  • g
+9

, (s/rmd_ver=1\.0\.10/rmd_ver=2.0.0/), :

sed -e 's/\(rmd_ver=\)1\.0\.10/\12.0.0/'
+2

, substitute, s/from_regex/to_result/. , 1.0.10, , [0-9.]. , , . sed

sed 's/rmd_ver=[0-9.]\+/rmd_ver=42/' filename

+ - , sed BRE ( ), .

If you want to avoid the coincidence of points at the ends, for example 1.2.3., you will have to change the regular expression to [0-9][0-9.]\+[0-9]to make sure that the first and last characters are not a point. Perhaps you also want to be able to match one digit, then you need to add an alternative (for example, /a|b/matches a or b) so that it matches:

sed 's/rmd_ver=\([0-9][0-9.]\+[0-9]\|[0-9]\)/rmd_ver=42/' filename
0
source
sed 's/\(rmd_ver=\).*[[:number:]]$/\1NEW_VAL/g'

you can replace NEW_VAL with the value you want to replace.

0
source

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


All Articles