search and replace block of code in all files in linux

风格不统一 提交于 2020-01-13 11:28:19

问题


This question is philosophically similar to a question that's come up time and time again here:

  • Search and replace text in all files of a linux directory
  • How to search-replace content within files in Ubuntu Linux?
  • Linux search and replace a complex string

But they (with the exception of the last one) all deal with simple replacements. I have a somewhat large block of code which appears in many files (I wish copy/pasting source code was punishable by law), and I need to replace it.

Is there anything that will help me out here? I want to avoid "sed"ifying the block (as is done in the third similar question above) because that will take the better part of a day. If I have to temporarily install some particular text editor, so be it.


回答1:


The nice thing about your question is that you're dealing with fixed strings rather than regular expressions...which makes the problem relatively simple. You could write something to do the job for you without too many problems.

The solution I've linked to isn't optimal, but it does work, and it doesn't rely on matching only opening/closing lines (that is, it only replaces verbatim matches). The basic idea is:

  • Read in the file that defines what we're looking for,
  • Read in the file that defines our replacement,
  • Iterate over all the other arguments, looking for the search string and replacing it with the replacement text



回答2:


If the opening and closing lines are unique you can delete the block and replace it with your code using with sed 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 only find one occurance of the block per file. As always, make a backup first.



来源:https://stackoverflow.com/questions/10557379/search-and-replace-block-of-code-in-all-files-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!