Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed - Replace immediate next string/word coming after a particular pattern

Tags:

shell

unix

sed

I'm a newbie to shell scripting and any help is much appreciated.

I have a pattern like this rmd_ver=1.0.10

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

like image 951
Zam Abdul Vahid Avatar asked Apr 02 '14 17:04

Zam Abdul Vahid


People also ask

How can I replace text after a specific word using sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input. txt.

How do you replace some text pattern with another text pattern in a file?

`sed` command is one of the ways to do replacement task. This command can be used to replace text in a string or a file by using a different pattern.

What does \b mean in sed?

\b marks a word boundary, either beginning or end. Now consider \b' . This matches a word boundary followed by a ' . Since ' is not a word character, this means that the end of word must precede the ' to match.


1 Answers

To replace any value till the end of the line:

sed -i 's/\(rmd_ver=\)\(.*\)/\1R/' file
  • sed -i 's/p/r/' file replace p with r in file
  • \( start first group
  • rmd_ver= search pattern
  • \) end first group
  • \( start second group
  • .* any characters
  • \) end second group
  • \1 back reference to the first group
  • R replacement text

To replace the exact pattern in any place of the line and possibly several times in one line:

sed -i 's/\(rmd_ver=\)\(1\.0\.10\)/\1R/g' file
  • \. escape special . into literal .
  • g to replace multiple occurrences in one line
like image 179
Andrey Avatar answered Oct 20 '22 19:10

Andrey