Finding and replacing a block of code in all files in Linux

This question is philosophically similar to the question that appears here again and again:

But they (with the exception of the latter) deal with simple replacements. I have a somewhat large block of code that appears in many files (I want to copy / paste the source code was punished by law) and I need to replace it.

Is there anything that helps me here? I want to avoid "sed" ifying the block (as is done in the third similar question above), because it will take most of the day. If I need to temporarily install a specific text editor, let it be.

+4
source share
2 answers

The good thing about your question is that you are dealing with fixed strings, not regular expressions ... which makes the problem relatively simple. You can write something to do this job without too much trouble.

The solution I'm connected to is not optimal, but it works, and it does not depend on matching only open / close strings (i.e. only replaces literal matches). Main idea:

  • Read in the file that determines what we are looking for,
  • Read in the file that defines our replacement,
  • Iterate over all other arguments, search for a search string, and replace it with replacement text
+4
source

If the opening and closing lines are unique, you can remove the block and replace it with code using the sed command using:

placeholder=somereallyuniquestringthatwillneverbematched for i in *.php; do # Remove original block using first and last line matching and add placeholder sed -i -e "/The text of the closing line/a\ $placeholder /The Text of the opening Line/,/The Text Of The Closing Line/d" "$i" # Replace placeholder with desired code sed -i -e "s/$placeholder/#include ('include/menu.php');/" "$i" done 

This will detect only one block detection for each file. As always, back up first.

+1
source

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


All Articles