I would like to replace a given string in a text file into by another, but with one extra detail.


If the file content's is :

Library Hello1
any text here
version: 0.1

Library Hello2
any text here

Library Hello3
any text here
version: 0.2

I would like to grep all lines containing the word Library and replace all "Library" by the other word, eg. "myStr". However this should only be done for those which version is, for example, 0.1. All the others should be ignored.

Please notice that the search/replace should be done inside each block of code. The blocks are delimited by ===== and -----.

Note: I can do search and replace, but I don't know how to simultaneously search for the version inside a block.

  • Is “any text here” always exactly one line? In this case I suggest that you use awk to read all parts of a section into three variables (for Library, any text, and version) and output the, possible modified, section after reading version or after reading --------------.
    – Renardo
    Commented Jun 21, 2018 at 10:08
  • Pedro, it appears you've suggested an edit with a new (separate) account; please register and use the first one so that you can edit your own posts.
    – Jeff Schaller
    Commented Jun 21, 2018 at 10:55

1 Answer 1


You can try this sed

sed '/^Library/!b;:A;N;/version/!bA;/0\.1$/s/^Library/myStr/' infile

Look first for Library.
If find get all the following line until version.
When find look for 0.1 and make change if it's ok.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .