Batch script to replace PHP short open tags with <?php

前端 未结 13 1879
轻奢々
轻奢々 2020-11-30 01:49

I have a large collection of php files written over the years and I need to properly replace all the short open tags into proper explicit open tags.

change \         


        
13条回答
  •  感情败类
    2020-11-30 02:48

    I'm going to streamline your regex for the purposes of this into what may work better, but I may be wrong since I haven't tested it on any real code.

    Let's say you're sitting in the base directory of your code, you could start with:

    find . -iname "*.php" -print0
    

    That will get you all .php files, separated by NULL characters, which is necessary in case any of them have spaces.

    find . -iname "*.php" -print0 | xargs -0 -I{} sed -n 's/\(<\?\)\([^a-zA-Z]\)/\1php\2/gp' '{}'
    

    This should get you most of the way there. It will find all the files, then for each one, run sed to replace the code. However, without the -i tag (used below), this won't actually touch your files, it will just send your code to your terminal. The -n suppresses normal output, and the p after the regex part tells it to print only lines that changed.

    Okay, if your results look correct, then you take the big step, which is replacing the files in-place. You should definitely back up all your files before attempting this!!!

    find . -iname "*.php" -print0 | xargs -0 -I{} sed -i 's/\(<\?\)\([^a-zA-Z]\)/\1php\2/g' '{}'
    

    That should about get the job done. Unfortunately, I have no PHP files lying around that use that syntax, so you're on your own to figure it out from here, but hopefully the mechanics of getting things done are a bit clearer now:

    1. Grab all the files with "find"
    2. Send that list of files to "xargs" (which does some command on the files one at a time
    3. Use "sed" and the syntax 's/to-change/changed/' to put your regex magic to work!

提交回复
热议问题