


Talk about the application of Shell in code refactoring_PHP tutorial
代码重构(Code refactoring)有时是很枯燥的,字符串替换之类的操作不仅乏味,而且还容易出错,好在有一些工具可用,以PHP为例,如:Rephactor,Scisr等等,不过现成的工具往往意味着不够灵活,所以今天我要说说Shell在代码重构中的应用。
先来个简单的,假设我们要把PHP文件中的foo_bar全都替换成fooBar,那么可以如下:
方法一,使用Sed:
shell> find /path -name "*.php" | xargs sed s/foo_bar/fooBar/g
方法二,使用AWK:
shell> find /path -name "*.php" | xargs awk { gsub(/foo_bar/, "fooBar"); print; }
注:为了简单,我把结果直接打印到终端屏幕了,至于如何保存,稍后会说明。
接着说个复杂的:假设某个PHP项目,以前使用类之前必须调用一个名为“includeClass”的方法,现在改用类自动加载的方式,所以要删除硬编码的includeClass调用,出于美观的考虑,如果includeClass下面一行是空行的话,也一起删除,同时考虑大小写不敏感的因素。
重构前的代码示例:
01 02 includeClass(...);
03 echo a;
04
05 echo b;
06 includeClass(...);
07 includeClass(...);
08
09
10 echo c;
11
12 echo d;
13 includeClass(...);
14
15
16 echo e;
17 ?>
重构后的代码示例:
01 02 echo a;
03
04 echo b;
05
06 echo c;
07
08 echo d;
09
10 echo e;
11 ?>
在动手前,我们需要先摸摸底,了解一下大概的情况:
shell> grep -I -ri includeClass /path | more
其中,grep命令的参数乍一看不好记,不过只要按照我说的方法记,就永远不会忘:前面的参数看做英文,后面的参数看做拼音。至于参数的具体含义,请参阅man文档。
方法一,使用Sed编写脚本script.sh:
#!/bin/sh
for PHP in $@; do
/bin/sed -i
/includeClass/I {
h
d
}
/^$/ {
x
/includeClass/Id
x
}
h
$PHP
done
注:篇幅所限,我把正则写的比较简单
Sed的缺点是代码可读性比较差,优点是代码较短。另外内置的“-i”选项可以直接完成保存,这是我喜欢Sed的原因之一。
方法二,使用AWK编写脚本script.sh:
#!/bin/sh
for PHP in $@; do
TMP=$(mktemp)
/bin/awk
BEGIN {
IGNORECASE = 1
}
/includeClass/ {
previous = $0
next
}
/^$/ {
if (previous ~ /includeClass/) {
previous = $0
next
}
}
{
previous = $0
print
}
$PHP > $TMP
/bin/cp -f $TMP $PHP
/bin/rm -f $TMP
done
注:篇幅所限,我把正则写的比较简单
AWK的缺点是代码比较长,优点是代码可读性较好。另外程序中是通过生成一个唯一的临时文件来完成保存的。
Reminder: Sometimes it is not appropriate to directly overwrite the original file. After all, there may be some things that have not been carefully considered. If you use SVN, you will not have such concerns, because even if the original file is overwritten, it can still be passed before submission. svn diff" command to check for errors. Even if it is submitted, it can be restored to the previous version.
What if the script.sh script is called? Here is the most general example:
shell> find /path -name "*.php" | xargs /path/to/script.sh
Sed is suitable for writing simple tasks, and AWK is best for complex tasks. Practical combat is the best way to learn. For details, you can refer to materials such as Sed One Line and AWK One Line.
Note: The Sed and AWK used in this article refer to the GNU version.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Deleted something important from your home screen and trying to get it back? You can put app icons back on the screen in a variety of ways. We have discussed all the methods you can follow and put the app icon back on the home screen. How to Undo Remove from Home Screen in iPhone As we mentioned before, there are several ways to restore this change on iPhone. Method 1 – Replace App Icon in App Library You can place an app icon on your home screen directly from the App Library. Step 1 – Swipe sideways to find all apps in the app library. Step 2 – Find the app icon you deleted earlier. Step 3 – Simply drag the app icon from the main library to the correct location on the home screen. This is the application diagram

The role and practical application of arrow symbols in PHP In PHP, the arrow symbol (->) is usually used to access the properties and methods of objects. Objects are one of the basic concepts of object-oriented programming (OOP) in PHP. In actual development, arrow symbols play an important role in operating objects. This article will introduce the role and practical application of arrow symbols, and provide specific code examples to help readers better understand. 1. The role of the arrow symbol to access the properties of an object. The arrow symbol can be used to access the properties of an object. When we instantiate a pair

The Linuxtee command is a very useful command line tool that can write output to a file or send output to another command without affecting existing output. In this article, we will explore in depth the various application scenarios of the Linuxtee command, from entry to proficiency. 1. Basic usage First, let’s take a look at the basic usage of the tee command. The syntax of tee command is as follows: tee[OPTION]...[FILE]...This command will read data from standard input and save the data to

As a programmer, I get excited about tools that simplify the coding experience. With the help of artificial intelligence tools, we can generate demo code and make necessary modifications as per the requirement. The newly introduced Copilot tool in Visual Studio Code allows us to create AI-generated code with natural language chat interactions. By explaining functionality, we can better understand the meaning of existing code. How to use Copilot to generate code? To get started, we first need to get the latest PowerPlatformTools extension. To achieve this, you need to go to the extension page, search for "PowerPlatformTool" and click the Install button

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension ".a" have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run ".a" files. This article will introduce how to comprehensively install and configure the Linux ".a" file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux ".a" file. What is L

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

The Go language is an open source programming language developed by Google and first released in 2007. It is designed to be a simple, easy-to-learn, efficient, and highly concurrency language, and is favored by more and more developers. This article will explore the advantages of Go language, introduce some application scenarios suitable for Go language, and give specific code examples. Advantages: Strong concurrency: Go language has built-in support for lightweight threads-goroutine, which can easily implement concurrent programming. Goroutin can be started by using the go keyword

The big model subverts everything, and finally got to the head of this editor. It is also an Agent that was created in just one sentence. Like this, give him an article, and in less than 1 second, fresh title suggestions will come out. Compared to me, this efficiency can only be said to be as fast as lightning and as slow as a sloth... What's even more incredible is that creating this Agent really only takes a few minutes. Prompt belongs to Aunt Jiang: And if you also want to experience this subversive feeling, now, based on the new Wenxin intelligent agent platform launched by Baidu, everyone can create their own intelligent assistant for free. You can use search engines, smart hardware platforms, speech recognition, maps, cars and other Baidu mobile ecological channels to let more people use your creativity! Robin Li himself
