Ubuntu: Use GREP to replace a body of text



Question:

What is best way to use GREP to replace text from in through </div> with walked down the path

The cat in the hat  jdlsknklnvlsdknld       ======>    The cat walked down the path  jkgsabkjkjksjakh  </div>  


Solution:1

Matching multiple lines can be fairly easily done using Perl.

perl -p0e 's# in .*</div># walked down the path.#sm'  

Briefly put,

  • -p0e turn Perl into a sed-like streaming multi-line processor.
  • The s#...#...# portion signifies that you want to replace all characters from in to </div> (the first clause) with walked down the path (the second clause).
  • sm roughly means "treat newline symbols as all other characters.

This answer assumes that the input text has only one such pattern.

Relevant documentation pages can be found here and here on Perl's official website.


Solution:2

Use grep to replace text? Good luck with that.

sed will do it for you:

sed 's/in the hat/walked down the path/;/The cat/,/<\/div>/ {/The cat/n;d}' file  

Notes

  • s/old/new/ replace old with new
  • ; separates commands
  • /begin/,/end/ operate within a range from the line with /begin/ to the line with /end/
  • {} grouping, for commands to use on the range
  • /The cat/n exclude the line with /The cat/ (do nothing and read the next line)
  • d delete (the rest of the lines in the range)

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »