Showing posts with label unix. Show all posts
Showing posts with label unix. Show all posts

Tuesday, 15 May 2007

Algorithm::Diff

before that, we need firstly to know something about metric,
here is document in chinese
http://www.core.org.cn/NR/rdonlyres/Sloan-School-of-Management/15-062Data-MiningSpring2003/78318536-A16C-4EC7-879F-C96C123AC7C4/0/linalg.pdf


Dynamic Programming
The following is an example of global sequence alignment using Needleman/Wunsch techniques. For this example, the two sequences to be globally aligned are

G A A T T C A G T T A (sequence #1)
G G A T C G A (sequence #2)

So M = 11 and N = 7 (the length of sequence #1 and sequence #2, respectively)

A simple scoring scheme is assumed where


* Si,j = 1 if the residue at position i of sequence #1 is the same as the residue at position j of sequence #2 (match score); otherwise
* Si,j = 0 (mismatch score)
* w = 0 (gap penalty)

Three steps in dynamic programming

1. Initialization
2. Matrix fill (scoring)
3. Traceback (alignment)

Initialization Step

The first step in the global alignment dynamic programming approach is to create a matrix with M + 1 columns and N + 1 rows where M and N correspond to the size of the sequences to be aligned.

Since this example assumes there is no gap opening or gap extension penalty, the first row and first column of the matrix can be initially filled with 0.

Matrix Fill Step

One possible (inefficient) solution of the matrix fill step finds the maximum global alignment score by starting in the upper left hand corner in the matrix and finding the maximal score Mi,j for each position in the matrix. In order to find Mi,j for any i,j it is minimal to know the score for the matrix positions to the left, above and diagonal to i, j. In terms of matrix positions, it is necessary to know Mi-1,j, Mi,j-1 and Mi-1, j-1.

For each position, Mi,j is defined to be the maximum score at position i,j; i.e.

Mi,j = MAXIMUM[
Mi-1, j-1 + Si,j (match/mismatch in the diagonal),
Mi,j-1 + w (gap in sequence #1),
Mi-1,j + w (gap in sequence #2)]


Note that in the example, Mi-1,j-1 will be red, Mi,j-1 will be green and Mi-1,j will be blue.

Using this information, the score at position 1,1 in the matrix can be calculated. Since the first residue in both sequences is a G, S1,1 = 1, and by the assumptions stated at the beginning, w = 0. Thus, M1,1 = MAX[M0,0 + 1, M1, 0 + 0, M0,1 + 0] = MAX [1, 0, 0] = 1.

A value of 1 is then placed in position 1,1 of the scoring matrix.

Since the gap penalty (w) is 0, the rest of row 1 and column 1 can be filled in with the value 1. Take the example of row 1. At column 2, the value is the max of 0 (for a mismatch), 0 (for a vertical gap) or 1 (horizontal gap). The rest of row 1 can be filled out similarly until we get to column 8. At this point, there is a G in both sequences (light blue). Thus, the value for the cell at row 1 column 8 is the maximum of 1 (for a match), 0 (for a vertical gap) or 1 (horizontal gap). The value will again be 1. The rest of row 1 and column 1 can be filled with 1 using the above reasoning.

Now let's look at column 2. The location at row 2 will be assigned the value of the maximum of 1(mismatch), 1(horizontal gap) or 1 (vertical gap). So its value is 1.

At the position column 2 row 3, there is an A in both sequences. Thus, its value will be the maximum of 2(match), 1 (horizontal gap), 1 (vertical gap) so its value is 2.

Moving along to position colum 2 row 4, its value will be the maximum of 1 (mismatch), 1 (horizontal gap), 2 (vertical gap) so its value is 2. Note that for all of the remaining positions except the last one in column 2, the choices for the value will be the exact same as in row 4 since there are no matches. The final row will contain the value 2 since it is the maximum of 2 (match), 1 (horizontal gap) and 2(vertical gap).

Using the same techniques as described for column 2, we can fill in column 3.

After filling in all of the values the score matrix is as follows:

Traceback Step

After the matrix fill step, the maximum alignment score for the two test sequences is 6. The traceback step determines the actual alignment(s) that result in the maximum score. Note that with a simple scoring algorithm such as one that is used here, there are likely to be multiple maximal alignments.

The traceback step begins in the M,J position in the matrix, i.e. the position that leads to the maximal score. In this case, there is a 6 in that location.

Traceback takes the current cell and looks to the neighbor cells that could be direct predacessors. This means it looks to the neighbor to the left (gap in sequence #2), the diagonal neighbor (match/mismatch), and the neighbor above it (gap in sequence #1). The algorithm for traceback chooses as the next cell in the sequence one of the possible predacessors. In this case, the neighbors are marked in red. They are all also equal to 5.

Since the current cell has a value of 6 and the scores are 1 for a match and 0 for anything else, the only possible predacessor is the diagonal match/mismatch neighbor. If more than one possible predacessor exists, any can be chosen. This gives us a current alignment of

(Seq #1) A
|
(Seq #2) A

So now we look at the current cell and determine which cell is its direct predacessor. In this case, it is the cell with the red 5.

The alignment as described in the above step adds a gap to sequence #2, so the current alignment is

(Seq #1) T A
|
(Seq #2) _ A

Once again, the direct predacessor produces a gap in sequence #2.

After this step, the current alignment is

(Seq #1) T T A
|
_ _ A

Continuing on with the traceback step, we eventually get to a position in column 0 row 0 which tells us that traceback is completed. One possible maximum alignment is :

Giving an alignment of :

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

An alternate solution is:

Giving an alignment of :

G _ A A T T C A G T T A
| | | | | |
G G _ A _ T C _ G _ _ A

There are more alternative solutions each resulting in a maximal global alignment score of 6. Since this is an exponential problem, most dynamic programming algorithms will only print out a single solution.

Now you are ready to explore an example using an advanced scoring scheme.
BL5495 Home Page
Eric C. Rouchka
ecr@ibc.wustl.edu


Advanced Dynamic Programming Tutorial
If you haven't looked at an example of a simple scoring scheme, please go to the simple dynamic programming example

The following is an example of global sequence alignment using Needleman/Wunsch techniques. For this example, the two sequences to be globally aligned are

G A A T T C A G T T A (sequence #1)
G G A T C G A (sequence #2)

So M = 11 and N = 7 (the length of sequence #1 and sequence #2, respectively)

An advanced scoring scheme is assumed where

* Si,j = 2 if the residue at position i of sequence #1 is the same as the residue at position j of sequence #2 (match score); otherwise
* Si,j = -1 (mismatch score)
* w = -2 (gap penalty)

Initialization Step

The first step in the global alignment dynamic programming approach is to create a matrix with M + 1 columns and N + 1 rows where M and N correspond to the size of the sequences to be aligned.

The first row and first column of the matrix can be initially filled with 0.

Matrix Fill Step

One possible (inefficient) solution of the matrix fill step finds the maximum global alignment score by starting in the upper left hand corner in the matrix and finding the maximal score Mi,j for each position in the matrix. In order to find Mi,j for any i,j it is minimal to know the score for the matrix positions to the left, above and diagonal to i, j. In terms of matrix positions, it is necessary to know Mi-1,j, Mi,j-1 and Mi-1, j-1.

For each position, Mi,j is defined to be the maximum score at position i,j; i.e.

Mi,j = MAXIMUM[
Mi-1, j-1 + Si,j (match/mismatch in the diagonal),
Mi,j-1 + w (gap in sequence #1),
Mi-1,j + w (gap in sequence #2)]

Note that in the example, Mi-1,j-1 will be red, Mi,j-1 will be green and Mi-1,j will be blue.

Using this information, the score at position 1,1 in the matrix can be calculated. Since the first residue in both sequences is a G, S1,1 = 2, and by the assumptions stated earlier, w = -2. Thus, M1,1 = MAX[M0,0 + 2, M1,0 - 2, M0,1 - 2] = MAX[2, -2, -2].

A value of 2 is then placed in position 1,1 of the scoring matrix. Note that there is also an arrow placed back into the cell that resulted in the maximum score, M[0,0].

Moving down the first column to row 2, we can see that there is once again a match in both sequences. Thus, S1,2 = 2. So M1,2 = MAX[M0,1 + 2, M1,1 - 2, M0,2 -2] = MAX[0 + 2, 2 - 2, 0 - 2] = MAX[2, 0, -2].

A value of 2 is then placed in position 1,2 of the scoring matrix and an arrow is placed to point back to M[0,1] which led to the maximum score.

Looking at column 1 row 3, there is not a match in the sequences, so S 1,3 = -1. M1,3 = MAX[M0,2 - 1, M1,2 - 2, M0,3 - 2] = MAX[0 - 1, 2 - 2, 0 - 2] = MAX[-1, 0, -2].

A value of 0 is then placed in position 1,3 of the scoring matrix and an arrow is placed to point back to M[1,2] which led to the maximum score.

We can continue filling in the cells of the scoring matrix using the same reasoning.

Eventually, we get to column 3 row 2. Since there is not a match in the sequences at this positon, S3,2 = -1. M3,2 = MAX[ M2,1 - 1, M3,1 - 2, M2,2 - 2] = MAX[0 - 1, -1 - 2, 1 -2] = MAX[-1, -3, -1].

Note that in the above case, there are two different ways to get the maximum score. In such a case, pointers are placed back to all of the cells that can produce the maximum score.

The rest of the score matrix can then be filled in. The completed score matrix will be as follows:

Traceback Step
After the matrix fill step, the maximum global alignment score for the two sequences is 3. The traceback step will determine the actual alignment(s) that result in the maximum score.

The traceback step begins in the M,J position in the matrix, i.e. the position where both sequences are globally aligned.

Since we have kept pointers back to all possible predacessors, the traceback step is simple. At each cell, we look to see where we move next according to the pointers. To begin, the only possible predacessor is the diagonal match.

This gives us an alignment of

A
|
A

Note that the blue letters and gold arrows indicate the path leading to the maximum score.

We can continue to follow the path using a single pointer until we get to the following situation.

The alignment at this point is

T C A G T T A
| | | |
T C _ G _ _ A

Note that there are now two possible neighbors that could result in the current score. In such a case, one of the neighbors is arbitrarily chosen.

Once the traceback is completed, it can be seen that there are only two possible paths leading to a maximal global alignment.

One possible path is as follows:

This gives an alignment of

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

The other possible path is as follows:

This gives an alignment of

G A A T T C A G T T A
| | | | | |
G G A T _ C _ G _ _ A

Remembering that the scoring scheme is +2 for a match, -1 for a mismatch, and -2 for a gap, both sequences can be tested to make sure that they result in a score of 3.

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

+ - + - + + - + - - +
2 1 2 2 2 2 2 2 2 2 2

2 - 1 + 2 - 2 + 2 + 2 - 2 + 2 - 2 - 2 + 2 = 3

G A A T T C A G T T A
| | | | | |
G G A T _ C _ G _ _ A

+ - + + - + - + - - +
2 1 2 2 2 2 2 2 2 2 2

2 - 1 + 2 + 2 - 2 + 2 - 2 + 2 - 2 - 2 + 2 = 3

so both of these alignments do indeed result in the maximal alignment score.
Eric C. Rouchka ecr@ibc.wustl.edu
Feb. 4, 1997
Compuational Molecular Biology Home Page

CVS使用CVS进行版本管理

#////////////////////////////////////////////////////////////////////// 
# 使用CVS进行版本管理 
# 2000-6-30 
# CVS 1.10.7 
# 
# 
# 
# Per Cederqvist et al 著 
# 廖斌 译 
# 感谢黄箐的输入和排版工作 
# copyrigh: GPL 
# 
#////////////////////////////////////////////////////////////////////// 
  

快捷内容索引 
1. 概述.........................................................1 
2. 代码仓库.....................................................7 
3. 使用CVS开始一个项目..........................................29 
4. 主干版本(Revision).........................................33 
5. 分支与合并...................................................41 
6. Recarsive behavior...........................................49 
7. 增加,删除,更名文件和目录...................................51 
8. 回顾开发历史.................................................57 
9. 放置二进制文件...............................................59 
10 多个开发者的同时工作........................................61 
11 主干版本管理.............................................71 
12 关键字替代................................................73 
13 跟踪第三方代码...............................................77 
14 你的系统如何同CVS交互........................................81 
15 特殊文件.....................................................83 
16 附录 
1) CVS命令导向..................................................85 
2) CVS命令快速参考............................................115 
3) 管理文件的参考习册.........................................127 
4) 影响CVS的所有环境变量......................................141 
5) CVS各版本之间的兼容性......................................143 
6) 遇到的问题.................................................145 
7) Credits....................................................153 
8) 对CVS和这本手册的总是处理..................................155 

目录 ...........................................................157 
    
  

1 概论 

这一章为从未用过CVS的人写的,也许以前也从未用过任何版本控制工具。 

1.1 什么是CVS? 

CVS是个版本控制系统,使用它你可以记录你原代码文件的历史。例如,当软件修改时有时会产生问题(*bugs这里被译为问题),并且你可能在做这次修改后很长时间不会发现这些问题。使用CVS,你可以容易地回顾老的代码版本去发现哪一次的修改导致这些问题。有时候这样会非常有帮助。 
  

你可能会保留你每一次的代码版本,这可能会浪费你很多的代码空间。CVS使用一种聪明的办法保存你的多个版本在一个文件中。它仅仅保留版本间的不同内容。如果你是一个项目中的一组成员之一,CVS也能够帮助你。除非你特别仔细,你很容易覆盖其他人的工作。一些编辑器,例如GNUEmacs,试图去判定一个文件是否被两人同时修改.不幸的是,如果一个人使用其它的编辑器时,这个安全方式将不再有效。CVS使用让不同开发者独立工作的方式解决了这个问题。每一个开发者的工作都在他自己的目录内,并且CVS将在每个开发者的工作完成后进行合并工作。 

CVS是由Dick Grune作为Shell脚本的一个分支而创建的,1986年10月,在它的第6个发行卷时,它被投递到新闻组comp.soures.unix。然而现在的CVS冲突算法中没有任何代码是从这些脚本中来的。 

在1989年3月,Brian Berlinor设计并编写了CVS的代码。Jett.Polk在以后帮助 Brian 完成了CVS 
模型的设计和商业版本支持。 

你可以通过不同的方式得到CVS,包括在Internet上自由的下载。如果你想下载CVS和其它CVS 
文章以得到更多的信息,请看: 

http://www.cyxlic.com 
http://www.loria.fr/~molli/cvs-index.html. 
  

有一个叫 info-cvs 的邮件列表是有关CVS的内容。订阅或取消订阅这个列表请发邮件到 

info-cvs-request@gnu.org 

如果你更喜欢Usenet新闻组,CVS的讨论组为 

Comp.software.confg.mgmt. 

在将来也许会建一个 

Comp.software.confg.mgmt.cvs 

的新闻组, 

但也许这会是Comp.software.confg.mgmt在有太多讨论之后的事情吧。 

你也许想订阅bug-cvs的邮件列表,这在附录H[BUGS]中有更多的信息。订阅它请发Email到 

bug-cvs-reqnest@gnu.org. 

1.2 CVS不能做的事 
(未译) 
2 
  

3 使用CVS开始一个项目 
======================= 
  

因为更改文件名并且把它们移动到另一个目录中不是经常发生的,因此你在开始一个新项目时要做的第一件事是考虑你的文件组织。更改文件名或移动文件并非不可能,但增加了理解上潜在的费解,并且CVS在更改名字的目录上特别的敏感。请参见7.4节[移动文件]。 
(* 译者注: 在Unix中改名和移动是相同的)。 

下一步做的事取决于手中的情况。 

3.1 建立文件 

第一步是在仓库中建立文件。这可以使用多种不同的方法来完成。 

-------------------------------------------------------------------- 

3.1.1 建立一个目录树 

当你开始使用CVS时,你可能已经有几个项目可以使用CVS进行管理了。在这种情况下,最容易的方法就是使用: "import"命令。一个例子是最容易解释如何使用它的。假定你现在有一些你想放到CVS中的文件在"wdir"中,并且你想让它们放在数据仓库中的如下目录: 

"$CVSROOT/yoyodyne/rdir" 

你可以使用如下命令: 

$cd wdir 
$cvs inport -m "Inported Sources" yoyodyne/rdir yoyo start 

如果你没有使用"-m"参数记录一个日志信息,CVS将调用一个编辑器(*译者注:通常是vi)并且提示输入信息。"yoyo"字符串是开发者标笺,"start"是发行标笺。他们没有什么特别的意义,仅仅是因为CVS的需要才放在这里。 

请参见第13章[跟踪代码],得到更多的这方面信息。 

你现在可以检查一下它是否有效了,然后可以删除你原来的代码目录。 

$cd 
$mv dir dir.orig 
$cvs checkout yoyodyne/dir 
$diff -r dir.orig yoyodyne/dir 
$rm -r dir.orig. 

为了避免偶然进入到你原来的目录中去编辑文件,删除原来的代码是个好主意。当然,在你删除之前保留一份备份到其它地方也是明智之举。 

"checkout"命令能使用模块名作为参数(正如前面所有例子)或是一个相对于$CVSROOT的路 
径,如同上面的例子。你应当检查CVS目录中的权限情况是否合适,应当使它们属于某一个 
特定的组。请参见2.2.2.节[文件权限]。 

如果你想"import"的一些文件是二进制代码,你可以使用一些特殊的方法表明这些文件是否 
是二进制文件。请参见C.2节[Wrappers]。 
  

------------------------------------------------------------------------------------ 

3.1.2 从其它版本控制系统建立文件 

如果你有一个其它版本控制系统维护的项目,例如RCS,你也许希望把这些文件放到CVS中, 
并且要保留这些文件的历史。以下是一些讨论。 

从RCS: 
如果你使用RCS,找到RCS文件??通常一个文件名叫"foo.c"的文件会有"RCS/foo.c,v"的RCS文 
件。(但它有可能在其它地方,请看RCS的文档以得到相关信息)。如果文件目录在CVS中不存 
在,那在CVS中创建它。然后把这些文件拷贝到CVS的仓库目录中(在仓库中的名字必须是带 
",v"的原文件;这些文件直接放在CVS中的这个目录下,而非"RCS"子目录中)。这是在CVS中 
一个为数不多的直接进入CVS仓库直接操作的情况,而没使用CVS命令。然后你就可以把它们 
在新的目录下"checkout"了。 

当你把RCS文件移动CVS中时,RCS文件应在未被锁定的状态,否则移动操作时CVS 将会出 
现一些问题。 

从其它版本控制工具 

许多版本控制工具都可以输出"RCS"格式的标准文档。如果你的版本控制工具可以做到这一 
点,直接输出RCS文件,然后按照上面的例子做就可以了。 

如果你的版本工具不能输出RCS文件,那么你必需要写一个脚本文件来,每次取出一个版本 
然后把它放到CVS中去。下面提到的"sccsarcs"脚本就是一个很好的例子。 

从SCCS: 

有一个"sccsarcs"的脚本文件可以做把SCCS的文件转化成RCS文件,这个文件放在CVS原代码 
目录的"contrib"目录中。注意: 

你必须在一台同时安装了RCS和SCCS的机器上运行它。并且,正如其它在"contrib."目录中的 
其它脚本一样。(你的方法也许是变化多端的) 

(*译者注:我并未查看过CVS的contrib目录:-(,因此不知道这下面都有些什么)。 

从PVCS: 

在"contrb"中有一个叫"pves-to-rcs"的脚本可以转换PVCS到RCS文件。你必须在一台同时有 
PVCS和RCS的机器上运行它。 

请看脚本中的注释以得到更多细节。 

3.1.3从无到有建立一个目录树 

建立一个新的项目,最容易的方法是建立一个空的目录树,如下所示: 

$mkdir tc 
$mkdir tc/man 
$mkdir tc/testing 

在这之后,你可以"import"这个(空)目录到仓库中去。 

$cd tc 
$cvs import -m "created directory structure"yoyodyne/dir yoyo 
start 

然后,当新增一个文件时,增加文件(或目录)到仓库中。请检查$CVSROOT中的权限是否正确。 

------------------------------------------------------------------------------------------- 

3.2 定义模块 

下一步是在"moduyes"文件中定义模块。这不是严格需要的,但模块能把相关的目录和文件容易 
关联起来。下面的例子可以充分演示如何定义模块。 

1. 得到模块文件的工作拷贝。 

$cvs checkout CVSROOT/modules 
$cd CVSROOT 

2. 
编辑这个文件并写入定义模块的行。请参见2.4节[管理文件的介绍]。有一个简单介绍,参见C.1节 
[模块文件]。有它的详细描述。你可以使用下面的行定义模块"tc": 

tc yoyodyne/tc 

3. 提交你的更改到仓库 

$cvs commit -m "Added tc module." modules 

4. 发行模块文件 

$cd 
$cvs release -d CVSROOT 

4 
======= 
  

5 分支与合并 
================== 
CVS允许你独立出一个派生的代码到一个分离的开发版本---分支。当你改变一个分支中的文 
件时,这些更改不会出现在主开发版本和其它分支版本中。 

在这之后你可以使用合并(merging)把这些变更从一个分支移动到另一个分支(或主开发版 
本)。合并涉及到使用“cvs update -j”命令,合并这些变更到一个工作目录。你可以确认 
(commit)这次版本,并且因此影响到拷贝这些变更到其它的分支。 

----------------------------------------------------------------------------------- 

5.1 何时应当创建一个分支 

假定tc.c发行版已完成。你正在继续开发tc.c,计划在2个月后发行1.1的版本。在不久以后你的 
客户开始抱怨说代码有些问题,你检查了一下1.0的发行版(请参见4.4节[标笺])并且找到了这 
个错误(这将会有一个小小的更正)。但是,这个当前的版本是处于一个不稳的状态,并且在下 
一个月才能有希望稳定下来。这样就没有办法去发行一个最新的现有版本去更正问题。 

这时就可以去创建基于这棵版本树1.0版的分支。你可以修改这棵树的分支而不影响到主干。当 
修订完成时,你可以选定是否要把它同主干合并或继续保留在这个分支里。 

----------------------------------------------------------------------------------- 

5.2 建立一个分支 

你可以使用“tag -b”去建立一个分支。例如,假定你在工作于一个工作拷贝中: 

$cvs tag -b rel_1_0_patches 

这将基于当前的拷贝分离出一个分支,并分配“rel_1_0_patches”的名字。 

懂得分支是在CVS仓库中创建,而非在工作拷贝中创建的是非常重要的。正上面的例 
子,创建一个基于当前版本的分支不会自动把当前的工作拷贝转到新的分支上。欲知 
详情,请看5.3节[进入 一个分支]。你也可以不参考任何工作拷贝而建立一个分支。 
你可以使用rtag命令: 

cvs rtag -b -r rel-1-0 rel-1-0-patches tc. 

“-r rel-1-0”说明这个分支是基于标志了rel-1-0的版本文件,它不是从最新的版本 
开始分支.这对需要从老的版本进行分支很有用(例如:当修订一个过去的稳定版本时) 

当使用“tag”标志,这个“-b”标志告诉rtag去创建一个分支(而非是这个版本的符号 
连接)。注意标记“rel-1-0”可能对不同的文件有不同的版本数字。因此,这个命令的结果 
是为tc模块建立了一个命名为“rel-1-0-patches”的新版本分支,它是基于标记为“rel-1-0” 
的版本树。 

----------------------------------------------------------------------------------- 

5.3 进入分支 

你可以通过两种方式进入分支:重新checkout或是从现存的拷贝进入。重新checkout使用 
checkout命令并带上“-r”标识,后面是这个分支的标笺(tag)名。(请看5.2[创建一个分支]): 

$cvs checkout -r rel-1-0-patches tc. 

或者如果你已有了一个拷贝,你可以使用“update -r”命令转到这个分支。 

$cvs update -r rel-1-0-patches tc. 

或者使用另一个等同的命令: 

$cd tc 
$cvs update -r rel-1-0-patches 

这对现有拷贝为主干代码或是其它分支都是有效的.上面的命令将把它转到命 
名的分支。同“update”命令相类似。“update -r”合并你所做的任何改变,请注 
意是否有冲突出现。 

一但你的工作拷贝已经转向一个特定的分支。它将一直保持在这个分支内,除非你 
又做了其它的操作。这意味着从这个工作拷贝checkin的变更将加到这个分支的新版 
本中,而不影响到主干版本和其它分支代码。 

想看一个工作拷贝是基于哪一个分支,可以使用“status”命令。在它们输出中查找 
一个“sticky tag”的域(请参见4.9节["sticky tag"],第38页).那就是你的当前分支号。 

$cvs status -v driver.c backend.c 

==================================================================== 
File: driver.c Status: Up-to-date 

Version: 1.7 Sat Dec S 18:25:54 1992 
RCS version: 1.7 /u/cvsroot/yoyodyne/tc/driver.c,v 
Sticky Tag: rel-1-0-patches (branch: 1.7.2) 
Sticky Date: (none) 
Stick Option: (none) 

Existing Tag: 
rel-1-0-patches (branck: 1.7.2) 
rel-1-0 (revision: 1.7) 
  

==================================================================== 
File: backend.c status: Up-to-date 

Version: 1.4 Tue Dec 1 14:39:01 
Rcs Version: 1.4 /u/cvsroot/yoyodyne/tc/ 
Sticky Tag: rel-1-0patches(branch:1.4.2) 
Sticky Date: (none) 
Sticky Option: (none) 

Existing Tag: 
Rel-1-0-patches (branch: 1.4.2) 
Rel-1-0 (revision: 1.4) 
Rel-0-4 (revision: 1.4) 
  

请不要因为每个文件的分支是不同(“1.7.2”和1.4.2")而迷惑。分支的标笺(tag) 
是相同的:"rel-1-0-patches",这些相同标笺的文件是相同分支的。在以上的例子中,分支建 
立之前,"driver.c" 比 "backend.c"有更多的变更,因此它们的版本编号是不同的。请参见5.4节 
[分支和主干版本号]去了解分支如何构建原理的细节。 

-------------------------------------------------------------------------------------- 

5.4 分支与主干版本 

通常,一个文件的主干版本历史是一个增长线(请看4.1[主干版本]页): 
  
    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 !
    +-----+    +-----+    +-----+    +-----+    +-----+
    
然而,CVS并不局限于线性的开发。主干版本可以分为不同的分支,每一个分支可 
以是一个独立的自我维护的开发线。而在一个分支中的变更可以很容易的转移到主干中。 
每一个分支均有一个分支号,由一个“.”分离的十进制奇数组成,分支号的编排依 
赖于它分离出的主线版本。使用分支号允许从一个特定版本分离出多个分支。 

所有的分支版本都依赖于它的原始分离版本号。下面的例子将展示这一点。 

 
                                                         +-------------+

                       1.2.2.3.2  分支 ->             +--! 1.2.2.3.2.1 !

                                                      !  +-------------+

                                                      !
                     +---------+    +---------+    +---------+
    1.2.2 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !----! 1.2.2.2 !
                  !  +---------+    +---------+    +---------+
                  !
                  !
    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !
                  !
                  !  +---------+    +---------+    +---------+
    1.2.4 分支->  +--! 1.2.4.1 !----! 1.2.4.2 !----! 1.2.4.2 !
                     +---------+    +---------+    +---------+

  

你是如何创建具体的分支号的细节通常不是你需要考虑的,但这里谈谈它如何工作。 

当CVS建立一个分支号时,它先得到第一个未用的偶数,开始的数字是2,例如你 
从6.4的主干版本创建分支时,分支号为6.4.2所有分支号码末位为0的号码用于CVS内 
部,(例如6.4.0)。(请参见5.5节[内部分支号]44页)分支1.1.1有特别的含义,请看13章 
[跟踪代码]。 

----------------------------------------------------------------------------------- 

5.5 内部分支号码 

这一节描述CVS的内部分支(magic branches) (* 译者注:magic branch 译为内部分支) 
特性。在大多数情况下,你不用考虑内部分支号码,CVS将为你进行管理。然而,在 
一些特定条件下,它将显现出来,因此理解它如何工作将是有用的。一般的,分支号 
码将由奇数个 "."分隔的十进制整数组成。请看4.1节[版本号码]。然而那并非完全是这 
样的,由于效率的原因,CVS有时插入一个额外的“0”在右末的第二个位置(1.2.4 
变为1.2.0.4,8.9.10.11.12变为8.9.10.11.0.12等)。 

CVS将会很好的将这些变换隐蔽在背后进行,但在一些地方,这种隐蔽并不完全: 

* 内部分支编号会出现在CVS的日志(log)文件中。 
* 你不能够对 "cvs admin" 使用符号分支名。 
  

你可以使用admin命令去为一个分支重新分配一个RCS希望的那样的符号名。如果 
R4patches是一个分配给分支1.4.2(内部分支编号为1.4.0.2)的一个文件"numbers.c"的 
命名,你可以使用如下命令: 

$cvs admin -NR4patches:1.4.2 numbers.c 

它将只在至少一个版本已经提交到这个分支时才会有效。请非常小心不要把一个标 
笺(tag)分配给了一个错误标识号(现在没有看到昨天的一个标笺是如何分配的)。 

---------------------------------------------------------------------------------- 

5.6 合并一个整个分支 

你可以合并一个分支到你的工作目录在“update”命令中“-j 分支号”的标识。使 
用“-j 分支号”将合并这个派生分支点与原版本的最新版之间的变更到你的工作目录 
“-j”的意思是“join”。 

我们现在来考察下面这棵树: 


    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 ! <- 主干
    +-----+    +-----+    +-----+    +-----+
                  !
                  !
                  !  +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !
                     +---------+    +---------+
                     

分支1.2.2分配了一个Rifix的名字.下面的例子假定模块"mod"只包含一个文件"m.c" 

$cvs checkout mod                             # 得到最新的1.4版 
$cvs update -j R1fix m.c                   # 合并所有在分支中的改变,即:1.2与1.2.2.2 
                                                                  # 之间的变化到这个文件的工作目
录. 

$cvs commit -m "Included R1fix    # 建立1.5版 
  

在合并时可能会发生冲突,如果这种情况发生,你可以在提交新版本之前解决它。请 
参见10.3节[冲突的例子]。 

如果你的原文件中包含关键字(请看第12章[关键字替代])。你可能会得到比严格意义 
上的冲突更多的冲突信息。请参见5.10节[合并和关键字],去了解如何避免这个问题。 
"checkout"命令也支持使用"-j"参数。下面的例子同上面所用的例子有相的效果。 

$cvs checkout -j R1fix mod. 
$cvs commit -m "Included R1fix" 

--------------------------------------------------------------------------------- 

5.7 从一个分支多次合并。 


    继续我们上面的例子。现在这棵树看起来是这样的:

    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !                              *
                  !                            *
                  !  +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !
                     +---------+    +---------+


正如上面所讨论的,分支1.2.2.2所引导的“*”号表示从Rifix分支到主干的合并。

    现在我们继续开发Rifix分支:

    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !                              *
                  !                            *
                  !  +---------+    +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !----! 1.2.2.3 !
                     +---------+    +---------+    +---------+

然后你可能会希望合并新的变更到主干中去。如果你仍使用“cvs update -j Fifix m.c" 
cvs将试图合并你已经合并过的东西,这可能写导致一些不希望发生的东西。 
  

因此,你必须表达清楚你希望只合并未被合并的内容的意思。这样需要使用两个 
“-j“参数。CVS合并从第一个“-j”的版本到第二个“-j”版本的变化。例如,在我们上面 

的例子中: 

cvs update -j 1.2.2.2 -j R1fix m.c 

如果出现的问题是你需要手工指定1.2.2.2的版本号,一个更好的方法是使用: 

cvs update -j R1fix:yesterday -j R1fix m.c 

然而,更好的方式是在每一次合并后重新放一个标笺给Rifix分支,然后使用标 
笺做后的合并: 

cvs update -j merged_from_Rifix_to_trunk -j R1fix m.c 

---------------------------------------------------------------------------------- 

5.8 合并两个任意版本之间的不同 

使用两个“-j”标志,这个update(和checkout)命令能合并两个任意不同的版本 
到你的工作目录。 

$cvs update -j 1.3 backend.c 

将把1.5版本恢复到1.3版本,所以一定要注意版本的顺序。 

如果你在操作多个文件时使用这个选择项,你必须了解在不同的文件之间,版本的 
数字可能是完全不同的。你必须使用标笺(tag)而不是使用版本号来完成多个文件 
的操作。使用两个“-j”操作也能会恢复增加或删除的文件。例如,假定你有一个 
叫“file1”的文件在在于1.1版本中,然后你在1.2版本中删除了它,下面是如何操作的例子: 

$cvs update -j 1.2 -j 1.1 file1 
file1 
$cvs commit -m test 
checking in file1; 
/tmp/cvs-sanity/cvsroot/first-dir/file1 file1,v 
new revision:1.3; previous revision:1.2 done 
$ 

------------------------------------------------------------------------------------ 

5.9 合并能添加和删除文件 

如果你在合并时的改变涉及到添加或删除一些文件,“update -j”将反映这些变化。 
例如: 

cvs update -A 
touch a b c 
cvs add a b c ; cvs ci -m "added" a b c 
cvs tag -b branchtag 
cvs update -r branchtag 
touch d ; cvs add d 
rm a ; cvs rm a 
cvs ci -m "added d , removed a" 
cvs update -A 
cvs update -j branchtag 
  

在这些命令之后(注意要commit),文件'a'将被删除,而文件'd'将被加入到主干。 

------------------------------------------------------------------------------------- 

5.10 合并和关键词 
  

如果你合并的文件包含关键词(参见第12章[关键词替代],73页),你通常将会在 
合并时得到 无数个冲突报告,因为在不同版本中非常不同。 

因此,你常需要在合并时使用“-kk”(参见12.4节[替代模式],75页)选择项。使用 
关键字名字,而非去扩展关键字的值的方法,这个功能选择项确保你合并的版本之间互相相 
同,而避免了冲突。 

   例如:假设你有一个文件如下:

                     +---------+
        br1   ->  +--! 1.1.2.1 !
                  !  +---------+
                  !
                  !
    +-----+    +-----+
    ! 1.1 !----! 1.2 !
    +-----+    +-----+  
  
  

并且你的当前工作目录拷贝为主干(1.2版本)。那么对于以下的合并将会产生一个 
冲突的结果。请看例子: 

$cat file1 
Key $Revision: 1.3 $ 
... 
$cvs update -j br1 
U file1 
RCS file: /cvsroot/first-dir/file1,v 
retrieving revision 1.1 
retrieving revision 1.1.2.1 
Meging differences between 1.1 and 1.1.2.1 into file1 
rscmerge: warning: conflicts during merge 
$ cat file1 
$<<<<<<< file1 
Key $Revision: 1.3 $ 
======= 
Key $Rerision: 1.1.2.1 $ 
$>>>>>>> 1.1.2.1 
... 
  

冲突发生在试图将1.1和1.1.2.1合并到你的工作目录中去的时候。因此,当这个 
关键词从“Revision:1.1"到"Revision:1.1.2.1"时,CVS将试图合并这个变化到 
你工作目录, 这就同你的目录中的变更“Revision:1.2"发生了冲突。 

以下是使用了:“-kk”后的例子: 

$cat file1 
key $Revision: 1.3 $ 
... 
$cvs update -kk -j br1 
V file1 
RCS file: /cvsroot/first-dir/file1,v 
retrieving revision 1.1 
retrieving revision 1.1.2.1 
Merging differences between 1.1 and 1.1.2.1 into file1 
$ cat file1 
key $Revision: 1.3 $ 
... 

在这里版本“1.1”和“1.1.2.1"都扩展为单纯的 "Revision",因此,合并时就不会 
发生冲突了。 

然而,使用 "-kk" 参数还一个主要的问题。即,它使用了CVS通常使用的关 
键字扩展模式。在特殊情况下,如果模式使用针对二进制文件的 "-kb" 
参数。这将会产生问题。因此,如果你的数据库中包括有二进制文件,你将 
必须手工处理这些问题,而不能使用 "-kk"。 

10 多个开发者同时工作 
--------------------- 

当多个开发者同时参与一个项目时,常常会发生冲突。一般经常发生的情况是两个人想 
同时编辑一个文件的时候。它的解决方法之一是文件锁定或是使用保留式的checkout,这种 
方法允许一个文件一次只允许一个人编辑。这是一些版本控制系统的唯一解决方式,包括 
RCS和SCCS。现在在CVS通常使用保留式checkout的方法是使用"CVS admin-1"命令(参见A-6-1AB 
[admin选择项])。在下面将解释这不是一种好的智能的解决方式,当它是许多人喜欢使用的 
一种方式。下面也将讲述可以使用适当的方法来避免两个人同时编辑一个文件,而非使用软件 
的方式强迫达到这一点。 

在CVS中默认的方法是"unreserved checkout"--非保留式的导出。在这种方法下,开发者 
可以同时在他们的工作拷贝中编辑一个文件。第一个提交工作的没有一种自动的方法可以知道 
另一个人在编辑文件。另一个人可能会在试图提交时得到一个错误信息。他们必须使用CVS命令 
使他们的工作拷贝同仓库的内容保持更新。这个操作是自动的。 

CVS可以支持facilitate多种不同的通信机制,而不会强迫去遵守某种规则,如"resered 
checkouts"那样。以下的部分描述这些不同的方式是如何工作的,和选择多种方式之间涉及到 
的一些问题。 

10.1 文件状态 

基于你对导出的文件使用过的操作,和这些文件在仓库中的版本使用过的操作,我们可以 
把一个文件分为几个状态。这个状态可以由"status"命令得到,它们是: 

up-to-date: 
对于正在使用的这个分支,文件同仓库中的最后版本保持一致。 

Locally Modified: 
你修改过文件,但没有"commit"。 

Locally added: 
使用了"add"命令增加文件,但没有"commit" 

Locally Removed: 
你使用了"remove"命令,但没有"commit" 

Needs checkout: 

其他人提交了一个更新的版本。这个状态的名字有些误导,你应当使用"update"而非 

"checkout"来更新新的版本。 

Needs Patch: 
象"Needs checkout"一样,但CVS服务将只给出Patch(补丁)文件,而非整个文件。而 
给出Patch和给出整个文件的效果是相同的。 

Needs Merge: 
一些人提交了一个更新版本,而你却修改过这些文件。 

File had conflicts on merge: 

这同"Locally Modified"相象,只是"update"命令给出了一个冲突信息。如果你还没有 
解决冲突,那么你需要解这个问题,解决冲突的方法参见10.3节[冲突的例子]. 

Unkown: 

CVS不知道关于这个文件的情况.例如,你创建了一个新文件,而没有使用"add"命令 

为了帮助弄清楚文件的状态,"status"也报告工作版本(working 
vevision),这是这个文件是从哪个版本来的,另外还报告"仓库版本"(Repository 
vevision)。这是这个文件在仓库中的这个版本分支的最后版本。 

"status"命令的选择项例在附录B[invoking cvs]。有关"sticky tag"和"sticky 
date"输出内容的信息,参见4.9节[sticky tags]。有关"sticky options"输出内容参见"-k"选择项, 
A.16.1节[update选择项]。 

你应当把"update"和"status"命令放在一起来认识。你使用"update"使你的文件更新到最 
新状态,你使用"status"命令来得到"update"命令将会做何种操作。(当然,仓库中的状态将可 
能会在你运行update之前变化)。事实上,如果你想使用一个命令得到比使用"status"正式的状 
态信息,你可以使用: 

$cvs -n -q -update 

这里"-n"选择项表示不真正执行update,而只显示状态;"-q"选择项表示不打印每个目录的 
名字。有关更多的关于"update"命令的住处参见附录B[使用CVS]。 

10.2 使一个文件更新到最版本 

当你想更新或是合并一个,使用update命令。对于一个不是最新版本的文件,这个命令大略等 
同于"checkout"命令:最新版本从仓库中提出并放到工作目录中。 

当你使用"update"命令时,你修改过的文件在任何情况下不会受到损害。如果在仓库中没有更 
新的版本,"update"时你的代码没有任何影响。当你编辑过一个文件,并且仓库中有更新版本,那 
么"update"将合并所有的变更到你的工作目录。 

例如,想象一个你导出了一个1.4版的文件并且开始编辑它,在某一时候其他人提交了1.5版,然 
后又提交了1.6版,如果你运行update命令,CVS将把1.4版到1.6版之间的变更放到你的文件中。 
如果在1.4版和1.6版之间的改变太靠近于的你一些变更的话,那么一个"覆盖"("overlop")冲突 
就发生了。在这种情况下将输出一个警告信息,然后结果保留的文件中包含了有冲突代码的两个版 
本,由特别的符号所分隔开。请参见A.16节[更新],可以得到关于"update"命令的一个完全的描述。 (http://www.fanqiang.com) 进入【UNIX论坛】

Version Control Systems

Version Control Systems Support
Synchronisation
Rollback
Experimentation
Internationalisation
Historical Record

Version Graphs
Extension
Split
Merge

A Version Control System lets you “check out” versions of a version control file


Locking Vs. Version Tracking

Locking
prevents complicated conflict resolution problems arising
also prevents duplication of effort (two programmers both doing the same thing at the same time)
Version tracking
prevents one person’s work being held up because someone else is using the file they want - or worse still, has forgotten to check the file back in
allows two developers to work on different sections of the same file at once

Friday, 11 May 2007

AWK_中文版

AWK是一种优良的文本处理工具。它不仅是 Linux 中也是任何环境中现有的功能最强大的数据处理发动机之一。这种编程及数据操作语言(其名称得自于它的创始人 Alfred Aho 、Peter Weinberger 和 Brian Kernighan 姓氏的首个字母)的最大功能取决于一个人所拥有的知识。 AWK 提供了极其强大的功能:可以进行样式装入、流控制、数学运算符、进程控制语句甚至于内置的变量和函数。它具备了一个完整的语言所应具有的几乎所有精美特性。实际上 AWK 的确拥有自己的语言: AWK 程序设计语言,三位创建者已将它正式定义为“样式扫描和处理语言”。它允许您创建简短的程序,这些程序读取输入文件、为数据排序、处理数据、对输入执行计算以及生成报表,还有无数其他的功能。

你可能对UNIX比较熟悉,但你可能对awk很陌生,这一点也不奇怪,的确,与其优秀的功能相比,awk还远没达到它应有的知名度。awk是什么?与其它大多数UNIX命令不同的是,从名字上看,我们不可能知道awk的功能:它既不是具有独立意义的英文单词,也不是几个相关单词的缩写。事实上,awk是三个人名的缩写,他们是:Aho、(Peter)Weinberg和 (Brain)Kernighan。正是这三个人创造了awk---一个优秀的样式扫描与处理工具。

   最简单地说, AWK 是一种用于处理文本的编程语言工具。AWK 在很多方面类似于 shell 编程语言,尽管 AWK 具有完全属于其本身的语法。它的设计思想来源于 SNOBOL4 、sed 、Marc Rochkind设计的有效性语言、语言工具 yacc 和 lex ,当然还从 C 语言中获取了一些优秀的思想。在最初创造 AWK 时,其目的是用于文本处理,并且这种语言的基础是,只要在输入数据中有模式匹配,就执行一系列指令。该实用工具扫描文件中的每一行,查找与命令行中所给定内容相匹配的模式。如果发现匹配内容,则进行下一个编程步骤。如果找不到匹配内容,则继续处理下一行。

   尽管操作可能会很复杂,但命令的语法始终是:

   awk '{pattern + action}' {filenames}

   其中 pattern 表示 AWK 在数据中查找的内容,而 action 是在找到匹配内容时所执行的一系列命令。花括号 ({}) 不需要在程序中始终出现,但它们用于根据特定的模式对一系列指令进行分组。

   gawk 是 AWK 的 GNU 版本。

一、AWK的功能是什么?

与sed和 grep很相似,awk是一种样式扫描与处理工具。但其功能却大大强于sed和grep。awk提供了极其强大的功能:它几乎可以完成grep和sed所能完成的全部工作,同时,它还可以可以进行样式装入、流控制、数学运算符、进程控制语句甚至于内置的变量和函数。它具备了一个完整的语言所应具有的几乎所有精美特性。实际上,awk的确拥有自己的语言:awk程序设计语言,awk的三位创建者已将它正式定义为:样式扫描和处理语言。

二、为什么使用awk?

即使如此,你也许仍然会问,我为什么要使用awk?

使用awk的第一个理由是基于文本的样式扫描和处理是我们经常做的工作,awk所做的工作有些象数据库,但与数据库不同的是,它处理的是文本文件,这些文件没有专门的存储格式,普通的人们就能编辑、阅读、理解和处理它们。而数据库文件往往具有特殊的存储格式,这使得它们必须用数据库处理程序来处理它们。既然这种类似于数据库的处理工作我们经常会遇到,我们就应当找到处理它们的简便易行的方法,UNIX有很多这方面的工具,例如sed 、grep、sort以及find等等,awk是其中十分优秀的一种。

使用awk的第二个理由是awk是一个简单的工具,当然这是相对于其强大的功能来说的。的确,UNIX有许嘤判愕墓ぞ撸鏤NIX天然的开发工具C语言及其延续C++就非常的优秀。但相对于它们来说,awk完成同样的功能要方便和简捷得多。这首先是因为awk提供了适应多种需要的解决方案:从解决简单问题的awk命令行到复杂而精巧的awk程序设计语言,这样做的好处是,你可以不必用复杂的方法去解决本来很简单的问题。例如,你可以用一个命令行解决简单的问题,而C不行,即使一个再简单的程序,C语言也必须经过编写、编译的全过程。其次,awk本身是解释执行的,这就使得awk程序不必经过编译的过程,同时,这也使得它与shell script程序能够很好的契合。最后,awk本身较C语言简单,虽然awk吸收了C语言很多优秀的成分,熟悉C语言会对学习awk有很大的帮助,但 awk本身不须要会使用C语言——一种功能强大但需要大量时间学习才能掌握其技巧的开发工具。

使用awk的第三个理由是awk是一个容易获得的工具。与C和C++语言不同,awk只有一个文件(/bin/awk),而且几乎每个版本的UNIX都提供各自版本的awk,你完全不必费心去想如何获得awk。但C语言却不是这样,虽然C语言是UNIX天然的开发工具,但这个开发工具却是单独发行的,换言之,你必须为你的UNIX版本的C语言开发工具单独付费(当然使用D版者除外),获得并安装它,然后你才可以使用它。

基于以上理由,再加上awk强大的功能,我们有理由说,如果你要处理与文本样式扫描相关的工作,awk应该是你的第一选择。在这里有一个可遵循的一般原则:如果你用普通的shell工具或shell script有困难的话,试试awk,如果awk仍不能解决问题,则便用C语言,如果C语言仍然失败,则移至C++。

三、awk的调用方式

前面曾经说过,awk提供了适应多种需要的不同解决方案,它们是:

1、 awk命令行,你可以象使用普通UNIX命令一样使用awk,在命令行中你也可以使用awk程序设计语言,虽然awk支持多行的录入,但是录入长长的命令行并保证其正确无误却是一件令人头疼的事,因此,这种方法一般只用于解决简单的问题。当然,你也可以在shell script程序中引用awk命令行甚至awk程序脚本。

2、使用-f选项调用awk程序。awk允许将一段awk程序写入一个文本文件,然后在awk命令行中用-f选项调用并执行这段程序。具体的方法我们将在后面的awk语法中讲到。

3、利用命令解释器调用awk程序:利用UNIX支持的命令解释器功能,我们可以将一段awk程序写入文本文件,然后在它的第一行加上:
#!/bin/awk -f
并赋予这个文本文件以执行的权限。这样做之后,你就可以在命令行中用类似于下面这样的方式调用并执行这段awk程序了。

$awk脚本文本名 待处理文件

awk的语法:

与其它UNIX命令一样,awk拥有自己的语法:

awk [ -F re] [parameter...] ['prog'] [-f progfile][in_file...]

参数说明:

-F re:允许awk更改其字段分隔符。

parameter: 该参数帮助为不同的变量赋值。

'prog': awk的程序语句段。这个语句段必须用单拓号:'和'括起,以防被shell解释。这个程序语句段的标准形式为:

'pattern {action}'

其中pattern参数可以是egrep正则表达式中的任何一个,它可以使用语法/re/再加上一些样式匹配技巧构成。与sed类似,你也可以使用","分开两样式以选择某个范围。关于匹配的细节,你可以参考附录,如果仍不懂的话,找本UNIX书学学grep和sed(本人是在学习ed时掌握匹配技术的)。 action参数总是被大括号包围,它由一系统awk语句组成,各语句之间用";"分隔。awk解释它们,并在pattern给定的样式匹配的记录上执行其操作。与shell类似,你也可以使用“#”作为注释符,它使“#”到行尾的内容成为注释,在解释执行时,它们将被忽略。你可以省略pattern和 action之一,但不能两者同时省略,当省略pattern时没有样式匹配,表示对所有行(记录)均执行操作,省略action时执行缺省的操作——在标准输出上显示。

-f progfile:允许awk调用并执行progfile指定有程序文件。progfile是一个文本文件,他必须符合awk的语法。

in_file:awk的输入文件,awk允许对多个输入文件进行处理。值得注意的是awk不修改输入文件。如果未指定输入文件,awk将接受标准输入,并将结果显示在标准输出上。awk支持输入输出重定向。

awk的记录、字段与内置变量:

前面说过,awk处理的工作与数据库的处理方式有相同之处,其相同处之一就是awk支持对记录和字段的处理,其中对字段的处理是grep和sed不能实现的,这也是awk优于二者的原因之一。在awk中,缺省的情况下总是将文本文件中的一行视为一个记录,而将一行中的某一部分作为记录中的一个字段。为了操作这些不同的字段,awk借用shell的方法,用$1,$2,$3...这样的方式来顺序地表示行(记录)中的不同字段。特殊地,awk用$0表示整个行(记录)。不同的字段之间是用称作分隔符的字符分隔开的。系统默认的分隔符是空格。awk允许在命令行中用-F re的形式来改变这个分隔符。事实上,awk用一个内置的变量FS来记忆这个分隔符。awk中有好几个这样的内置变量,例如,记录分隔符变量RS、当前工作的记录数NR等等,本文后面的附表列出了全部的内置变量。这些内置的变量可以在awk程序中引用或修改,例如,你可以利用NR变量在模式匹配中指定工作范围,也可以通过修改记录分隔符RS让一个特殊字符而不是换行符作为记录的分隔符。

例:显示文本文件myfile中第七行到第十五行中以字符%分隔的第一字段,第三字段和第七字段:

awk -F % 'NR==7,NR==15 {printf $1 $3 $7}'

四、awk的内置函数

awk 之所以成为一种优秀的程序设计语言的原因之一是它吸收了某些优秀的程序设计语言(例如C)语言的许多优点。这些优点之一就是内置函数的使用,awk定义并支持了一系列的内置函数,由于这些函数的使用,使得awk提供的功能更为完善和强大,例如,awk使用了一系列的字符串处理内置函数(这些函数看起来与C 语言的字符串处理函数相似,其使用方式与C语言中的函数也相差无几),正是由于这些内置函数的使用,使awk处理字符串的功能更加强大。本文后面的附录中列有一般的awk所提供的内置函数,这些内置函数也许与你的awk版本有些出入,因此,在使用之前,最好参考一下你的系统中的联机帮助。

作为内置函数的一个例子,我们将在这里介绍awk的printf函数,这个函数使得awk与c语言的输出相一致。实际上,awk中有许多引用形式都是从C语言借用过来的。如果你熟悉C语言,你也许会记得其中的printf函数,它提供的强大格式输出功能曾经带我们许多的方便。幸运的是,我们在awk中又和它重逢了。awk中printf几乎与C语言中一模一样,如果你熟悉C语言的话,你完全可以照C语言的模式使用awk中的printf。因此在这里,我们只给出一个例子,如果你不熟悉的话,请随便找一本C语言的入门书翻翻。

例:显示文件myfile中的行号和第3字段:

$awk '{printf"%03d%sn",NR,$1}' myfile

五、在命令行使用awk

按照顺序,我们应当讲解awk程序设计的内容了,但在讲解之前,我们将用一些例子来对前面的知识进行回顾,这些例子都是在命令行中使用的,由此我们可以知道在命令行中使用awk是多么的方便。这样做的原因一方面是为下面的内容作铺垫,另一方面是介绍一些解决简单问题的方法,我们完全没有必要用复杂的方法来解决简单的问题----既然awk提供了较为简单的方法的话。

例:显示文本文件mydoc匹配(含有)字符串"sun"的所有行。

$awk '/sun/{print}' mydoc

由于显示整个记录(全行)是awk的缺省动作,因此可以省略action项。

$awk '/sun/' mydoc

例:下面是一个较为复杂的匹配的示例:

$awk '/[Ss]un/,/[Mm]oon/ {print}' myfile

它将显示第一个匹配Sun或sun的行与第一个匹配Moon或moon的行之间的行,并显示到标准输出上。

例:下面的示例显示了内置变量和内置函数length()的使用:

$awk 'length($0)>80 {print NR}' myfile

该命令行将显示文本myfile中所有超过80个字符的行号,在这里,用$0表示整个记录(行),同时,内置变量NR不使用标志符'$'。

例:作为一个较为实际的例子,我们假设要对UNIX中的用户进行安全性检查,方法是考察/etc下的passwd文件,检查其中的passwd字段(第二字段)是否为"*",如不为"*",则表示该用户没有设置密码,显示出这些用户名(第一字段)。我们可以用如下语句实现:

#awk -F: '$2=="" {printf("%s no password!n",$1' /etc/passwd

在这个示例中,passwd文件的字段分隔符是“:”,因此,必须用-F:来更改默认的字段分隔符,这个示例中也涉及到了内置函数printf的使用。

六、awk的变量

如同其它程序设计语言一样,awk允许在程序语言中设置变量,事实上,提供变量的功能是程序设计语言的其本要求,不提供变量的程序设计语言本人还从未见过。

awk 提供两种变量,一种是awk内置的变量,这前面我们已经讲过,需要着重指出的是,与后面提到的其它变量不同的是,在awk程序中引用内置变量不需要使用标志符"$"(回忆一下前面讲过的NR的使用)。awk提供的另一种变量是自定义变量。awk允许用户在awk程序语句中定义并调用自已的变量。当然这种变量不能与内置变量及其它awk保留字相同,在awk中引用自定义变量必须在它前面加上标志符"$"。与C语言不同的是,awk中不需要对变量进行初始化, awk根据其在awk中第一次出现的形式和上下文确定其具体的数据类型。当变量类型不确定时,awk默认其为字符串类型。这里有一个技巧:如果你要让你的 awk程序知道你所使用的变量的明确类型,你应当在在程序中给它赋初值。在后面的实例中,我们将用到这一技巧。

七、运算与判断

作为一种程序设计语言所应具有的特点之一,awk支持多种运算,这些运算与C语言提供的几本相同:如+、-、*、/、%等等,同时,awk也支持C语言中类似++、--、+=、-=、=+、=-之类的功能,这给熟悉C语言的使用者编写awk程序带来了极大的方便。作为对运算功能的一种扩展,awk还提供了一系列内置的运算函数(如log、sqr、cos、sin等等)和一些用于对字符串进行操作(运算)的函数(如length、substr等等)。这些函数的引用大大的提高了awk的运算功能。

作为对条件转移指令的一部分,关系判断是每种程序设计语言都具备的功能,awk也不例外。 awk中允许进行多种测试,如常用的==(等于)、!=(不等于)、>(大于)、<(小于)、>=(大于等于)、>=(小于等于)等等,同时,作为样式匹配,还提供了~(匹配于)和!~(不匹配于)判断。

作为对测试的一种扩充,awk也支持用逻辑运算符:!(非)、&&(与)、||(或)和括号()进行多重判断,这大大增强了awk的功能。本文的附录中列出了awk所允许的运算、判断以及操作符的优先级。

八、awk的流程控制

流程控制语句是任何程序设计语言都不能缺少的部分。任何好的语言都有一些执行流程控制的语句。awk提供的完备的流程控制语句类似于C语言,这给我们编程带来了极大的方便。

1、BEGIN和END:

在awk 中两个特别的表达式,BEGIN和END,这两者都可用于pattern中(参考前面的awk语法),提供BEGIN和END的作用是给程序赋予初始状态和在程序结束之后执行一些扫尾的工作。任何在BEGIN之后列出的操作(在{}内)将在awk开始扫描输入之前执行,而END之后列出的操作将在扫描完全部的输入之后执行。因此,通常使用BEGIN来显示变量和预置(初始化)变量,使用END来输出最终结果。
例:累计销售文件xs中的销售金额(假设销售金额在记录的第三字段):

$awk
>'BEGIN { FS=":";print "统计销售金额";total=0}
>{print $3;total=total+$3;}
>END {printf "销售金额总计:%.2f",total}' sx
(注:>是shell提供的第二提示符,如要在shell程序awk语句和awk语言中换行,则需在行尾加反斜杠)

在这里,BEGIN预置了内部变量FS(字段分隔符)和自定义变量total,同时在扫描之前显示出输出行头。而END则在扫描完成后打印出总合计。

2、流程控制语句

awk提供了完备的流程控制语句,其用法与C语言类似。下面我们一一加以说明:

2.1、if...else语句:

格式:
if(表达式)
语句1
else
语句2

格式中"语句1"可以是多个语句,如果你为了方便awk判断也方便你自已阅读,你最好将多个语句用{}括起来。awk分枝结构允许嵌套,其格式为:

if(表达式1)
{if(表达式2)
语句1
else
语句2
}
语句3
else {if(表达式3)
语句4
else
语句5
}
语句6

当然实际操作过程中你可能不会用到如此复杂的分枝结构,这里只是为了给出其样式罢了。

2.2、while语句

格式为:

while(表达式)
语句

2.3、do-while语句

格式为:

do
{
语句
}while(条件判断语句)

2.4、for语句

格式为:

for(初始表达式;终止条件;步长表达式)
{语句}

在awk 的 while、do-while和for语句中允许使用break,continue语句来控制流程走向,也允许使用exit这样的语句来退出。break 中断当前正在执行的循环并跳到循环外执行下一条语句。continue从当前位置跳到循环开始处执行。对于exit的执行有两种情况:当exit语句不在 END中时,任何操作中的exit命令表现得如同到了文件尾,所有模式或操作执行将停止,END模式中的操作被执行。而出现在END中的exit将导致程序终止。

例:为了

九、awk中的自定义函数

定义和调用用户自己的函数是几乎每个高级语言都具有的功能,awk也不例外,但原始的awk并不提供函数功能,只有在nawk或较新的awk版本中才可以增加函数。

函数的使用包含两部分:函数的定义与函数调用。其中函数定义又包括要执行的代码(函数本身)和从主程序代码传递到该函数的临时调用。

awk函数的定义方法如下:

function 函数名(参数表){
函数体
}

在gawk中允许将function省略为func,但其它版本的awk不允许。函数名必须是一个合法的标志符,参数表中可以不提供参数(但在调用函数时函数名后的一对括号仍然是不可缺少的),也可以提供一个或多个参数。与C语言相似,awk的参数也是通过值来传递的。

在awk 中调用函数比较简单,其方法与C语言相似,但awk比C语言更为灵活,它不执行参数有效性检查。换句话说,在你调用函数时,可以列出比函数预计(函数定义中规定)的多或少的参数,多余的参数会被awk所忽略,而不足的参数,awk将它们置为缺省值0或空字符串,具体置为何值,将取决于参数的使用方式。

awk函数有两种返回方式:隐式返回和显式返回。当awk执行到函数的结尾时,它自动地返回到调用程序,这是函数是隐式返回的。如果需要在结束之前退出函数,可以明确地使用返回语句提前退出。方法是在函数中使用形如:return 返回值 格式的语句。

例:下面的例子演示了函数的使用。在这个示例中,定义了一个名为print_header的函数,该函数调用了两个参数FileName和PageNum, FileName参数传给函数当前使用的文件名,PageNum参数是当前页的页号。这个函数的功能是打印(显示)出当前文件的文件名,和当前页的页号。完成这个功能后,这个函数将返回下一页的页号。

nawk
>'BEGIN{pageno=1;file=FILENAME
>pageno=print_header(file,pageno);#调用函数print_header
>printf("当前页页号是:%dn",pageno);
>}

>#定义函数print_header
>function print_header(FileName,PageNum){
>printf("%s %dn",FileName,PageNum); >PageNum++;return PageNUm;
>}
>}' myfile


执行这个程序将显示如下内容:

myfile 1
当前页页号是:2

十、awk高级输入输出

1.读取下一条记录:

awk的next语句导致awk读取下一个记录并完成模式匹配,然后立即执行相应的操作。通常它用匹配的模式执行操作中的代码。next导致这个记录的任何额外匹配模式被忽略。
2.简单地读取一条记录

awk 的 getline语句用于简单地读取一条记录。如果用户有一个数据记录类似两个物理记录,那么getline将尤其有用。它完成一般字段的分离(设置字段变量$0 FNR NF NR)。如果成功则返回1,失败则返回0(到达文件尾)。如果需简单地读取一个文件,则可以编写以下代码:

例:示例getline的使用

{while(getline==1)
{
#process the inputted fields
}
}

也可以使getline保存输入数据在一个字段中,而不是通过使用getline variable的形式处理一般字段。当使用这种方式时,NF被置成0,FNR和NR被增值。

用户也可以使用getline<"filename"方式从一个给定的文件中输入数据,而不是从命令行所列内容输入数据。此时,getline将完成一般字段分离(设置字段变量$0和NF)。如果文件不存在,返回-1,成功,返回1,返回0表示失败。用户可以从给定文件中读取数据到一个变量中,也可以用stdin(标准输入设备)或一个包含这个文件名的变量代替filename。值得注意的是当使用这种方式时不修改FNR和NR。

另一种使用getline语句的方法是从UNIX命令接受输入,例如下面的例子:

例:示例从UNIX命令接受输入

{while("who -u"|getline)
{
#process each line from the who command
}
}

当然,也可以使用如下形式:

"command" | getline variable

3.关闭文件:

awk中允许在程序中关闭一个输入或输出文件,方法是使用awk的close语句。

close("filename"t

filename可以是getline打开的文件(也可以是stdin,包含文件名的变量或者getline使用的确切命令)。或一个输出文件(可以是stdout,包含文件名的变量或使用管道的确忻睿?

4.输出到一个文件:

awk中允许用如下方式将结果输出到一个文件:

printf("hello word!n"t>"datafile"
或
printf("hello word!n"t>>"datafile"

5.输出到一个命令

awk中允许用如下方式将结果输出到一个命令:

printf("hello word!n"t|"sort-t','"

十一、awk与shell script混合编程

因为awk可以作为一个shell命令使用,因此awk能与shell批处理程序很好的融合在一起,这给实现awk与shell程序的混合编程提供了可能。实现混合编程的关键是awk与shell script之间的对话,换言之,就是awk与shell script之间的信息交流:awk从shell script中获取所需的信息(通常是变量的值)、在awk中执行shell命令行、shell script将命令执行的结果送给awk处理以及shell script读取awk的执行结果等等。

1.awk读取Shell script程序变量

在awk中我们可以通过“'$变量名'”的方式读取sell scrpit程序中的变量。

例:在下面的示例中,我们将读取sell scrpit程序中的变量Name,该变量存放的是文本myfile的撰写者,awk将打印出这个人名。

$cat writename
:
# @(#)
#
.
.
.
Name="张三" nawk 'BEGIN {name="'Name'"; printf("t%st撰写者%sn",FILENAME,name"t;}
{...}END{...}' myfile
.
.
.

2.将shell命令的执行结果送给awk处理

作为信息传送的一种方法,我们可以将一条shell命令的结果通过管道线(|)传递给awk处理:

例:示例awk处理shell命令的执行结果

$who -u | awk '{printf("%s正在执行%sn",$2,$1)}'

该命令将打印出注册终端正在执行的程序名。

3.shell script程序读awk的执行结果

为了实现shell script程序读取awk执行的结果,我们可以采取一些特殊的方法,例如我们可以用变量名=`awk语句`的形式将awk执行的结果存放入一个 shell script变量。当然也可以用管道线的方法将awk执行结果传递给shell script程序处理。

例:作为传送消息的机制之一,UNIX提供了一个向其所有用户传送消息的命令wall(意思是write to all写给所有用户),该命令允许向所有工作中的用户(终端)发送消息。为此,我们可以通过一段shell批处理程序wall.shell来模拟这一程序(事实上比较老的版本中wall就是一段shell批处理程序:
$cat wall.shell
:
# @(#) wall.shell:发送消息给每个已注册终端
#
cat >/tmp/$$
#用户录入消息文本 who -u | awk '{print $2}' | while read tty
do
cat /tmp/$$>$tty
done

在这个程序里,awk接受who -u命令的执行结果,该命令打印出所有已注册终端的信息,其中第二个字段是已注册终端的设备名,因此用awk命令析出该设备名,然后用while read tty语句循环读出这些文件名到变量(shell script变量)tty中,作为信息传送的终结地址。

4.在awk中执行shell命令行----嵌入函数system()

system()是一个不适合字符或数字类型的嵌入函数,该函数的功能是处理作为参数传递给它的字符串。system对这个参数的处理就是将其作为命令处理,也就是说将其当作命令行一样加以执行。这使得用户在自己的awk程序需要时可以灵活地执行命令或脚本。

例:下面的程序将使用system嵌入函数打印用户编制好的报表文件,这个文件存放在名为myreport.txt的文件中。为简约起见,我们只列出了其END部分:

.
.
.
END {close("myreport.txt"t;system("lp myreport.txt"t;}

在这个示例中,我们首先使用close语句关闭了文件myreport.txt文件,然后使用system嵌入函数将myreport.txt送入打印机打印。

写到这里,我不得不跟朋友们说再见了,实在地说,这些内容仍然是awk的初步知识,电脑永远是前进的科学,awk也不例外,本篇所能做的只是在你前行的漫漫长途中铺平一段小小开端,剩下的路还得靠你自己去走。老实说,如果本文真能给你前行的路上带来些许的方便,那本人就知足了!

如对本篇有任何疑问,请E-mail To:Chizlong@yeah.net或到主页http://chizling.yeah.net中留言。


附录:

1.awk的常规表达式元字符

换码序列
^ 在字符串的开头开始匹配
$ 在字符串的结尾开始匹配
. 与任何单个字符串匹配
[ABC] 与[]内的任一字符匹配
[A-Ca-c] 与A-C及a-c范围内的字符匹配(按字母表顺序)
[^ABC] 与除[]内的所有字符以外的任一字符匹配
Desk|Chair 与Desk和Chair中的任一个匹配
[ABC][DEF] 关联。与A、B、C中的任一字符匹配,且其后要跟D、E、F中的任一个字符。
* 与A、B或C中任一个出现0次或多次的字符相匹配
+ 与A、B或C中任何一个出现1次或多次的字符相匹配
? 与一个空串或A、B或C在任何一个字符相匹配
(Blue|Black)berry 合并常规表达式,与Blueberry或Blackberry相匹配

2.awk算术运算符

运算符 用途
------------------
x^y x的y次幂
x**y 同上
x%y 计算x/y的余数(求模)
x+y x加y
x-y x减y
x*y x乘y
x/y x除y
-y 负y(y的开关符号);也称一目减
++y y加1后使用y(前置加)
y++ 使用y值后加1(后缀加)
--y y减1后使用y(前置减)
y-- 使用后y减1(后缀减)
x=y 将y的值赋给x
x+=y 将x+y的值赋给x
x-=y 将x-y的值赋给x
x*=y 将x*y的值赋给x
x/=y 将x/y的值赋给x x%=y 将x%y的值赋给x
x^=y 将x^y的值赋给x
x**=y 将x**y的值赋给x

3.awk允许的测试:

操作符 含义

x==y x等于y
x!=y x不等于y
x>y x大于y
x>=y x大于或等于y
xx<=y x小于或等于y?
x~re x匹配正则表达式re?
x!~re x不匹配正则表达式re?

4.awk的操作符(按优先级升序排列)

= 、+=、 -=、 *= 、/= 、 %=
||
&&
> >= < <= == != ~ !~
xy (字符串连结,'x''y'变成"xy")
+ -
* / %
++ --

5.awk内置变量(预定义变量)

说明:表中v项表示第一个支持变量的工具(下同):A=awk,N=nawk,P=POSIX awk,G=gawk

V 变量 含义 缺省值
--------------------------------------------------------
N ARGC 命令行参数个数
G ARGIND 当前被处理文件的ARGV标志符
N ARGV 命令行参数数组
G CONVFMT 数字转换格式 %.6g
P ENVIRON UNIX环境变量
N ERRNO UNIX系统错误消息
G FIELDWIDTHS 输入字段宽度的空白分隔字符串
A FILENAME 当前输入文件的名字
P FNR 当前记录数
A FS 输入字段分隔符 空格
G IGNORECASE 控制大小写敏感0(大小写敏感)
A NF 当前记录中的字段个数
A NR 已经读出的记录数
A OFMT 数字的输出格式 %.6g
A OFS 输出字段分隔符 空格
A ORS 输出的记录分隔符 新行
A RS 输入的记录他隔符 新行
N RSTART 被匹配函数匹配的字符串首
N RLENGTH 被匹配函数匹配的字符串长度
N SUBSEP 下标分隔符 "34"

6.awk的内置函数

V 函数 用途或返回值
------------------------------------------------
N gsub(reg,string,target) 每次常规表达式reg匹配时替换target中的string
N index(search,string) 返回string中search串的位置
A length(string) 求串string中的字符个数
N match(string,reg) 返回常规表达式reg匹配的string中的位置
N printf(format,variable) 格式化输出,按format提供的格式输出变量variable。
N split(string,store,delim) 根据分界符delim,分解string为store的数组元素
N sprintf(format,variable) 返回一个包含基于format的格式化数据,variables是要放到串中的数据
G strftime(format,timestamp) 返回一个基于format的日期或者时间串,timestmp是systime()函数返回的时间
N sub(reg,string,target) 第一次当常规表达式reg匹配,替换target串中的字符串
A substr(string,position,len) 返回一个以position开始len个字符的子串
P totower(string) 返回string中对应的小写字符
P toupper(string) 返回string中对应的大写字符
A atan(x,y) x的余切(弧度)
N cos(x) x的余弦(弧度)
A exp(x) e的x幂
A int(x) x的整数部分
A log(x) x的自然对数值
N rand() 0-1之间的随机数
N sin(x) x的正弦(弧度)
A sqrt(x) x的平方根
A srand(x) 初始化随机数发生器。如果忽略x,则使用system()
G system() 返回自1970年1月1日以来经过的时间(按秒计算

Friday, 20 April 2007

regular_expression

Shell Metacharacters: Special characters are interpreted by the shell for expansion unless they are quoted or escaped
  • * metacharacter means any srtings of zero or more characters, eg *.*,
  • ? matches any single character
  • [] matches any of the eclosed charcter. [a-z] or [!abc]
  • ` substitutes the output of a command.


Avoiding Shell Expansion: The character needs to be quoted or escaped

quoted:

  • "" everything between " and " is taken literally, except for : $ ` ' " .
  • '' everything between ' and ' is taken literally except for ' . we can embed another ' within a pare of ' using escaping.


Escaped: using \

  • The character following a backslash \ is taken literally.
  • Use \ within ″ ″ or ’ ’ to escape ″, $, and ′ when necessary.

p11

shell_script

Environment Variables: used by shell and by other programs:


  • [zliybsj2@unnc-cslinux ~]$ echo $PATH
  • /usr/kerberos/bin:/usr/local/bin:
  • /bin:/usr/bin:/usr/X11R6/bin:/opt/SUNWappserver/jdk/bin/:
  • /usr/NX/bin:/home/domain/zliybsj2/bi
  • [zliybsj2@unnc-cslinux ~]$ echo $TERM
  • xterm
  • [zliybsj2@unnc-cslinux ~]$ echo $HOME
  • /home/domain/zliybsj2
  • [zliybsj2@unnc-cslinux ~]$ echo $PS1
  • [\u@\h \W]\$
  1. using all capitals,
  2. using echo to get the value of a variable.
  3. variables are expanded by the shell before he command is executed.
  4. environment variables can be used by any program.
  5. variables change is only visible in the current shell.child process don't automatically inherit the environmrnt variables from their parent. using export to let proecessed get the changed value, eg export VAR=value, then $VAR in child process is value, or stay same. using : to add somthing to PATH, eg, export PATH=$PATH:new stuff

PATH:

  1. it tells UNIX where to look for executables
  2. when you type the name of a program, the shell will look for it in your PATH
  3. ecah directory seperated by a colon
  4. changed PATH can only live in current widow.

shell script:

  1. the shell is a command interpreter
  2. shell script is a text file contains all command you want to group, which is executed in a sub shell.
  3. first line is a specially comment: #!/bin/sh tell program which kind of shell will be using to execut this shell.

chomd :

  1. chmod o-r coursework
  2. chmod u+x shellscript
  3. chmod a+x shellscript
  4. chmod +x directory

input and output:

  • echo works like Java's println.
  • argument: $0, $1, $2,...... $#

conditionals:

  • if ...
  • then ...
  • else if ...
  • else ...
  • fi

read: to get input to interacte with users

can have more than one argument. will bind the first word of input to the first variable and bind the rest to the second. this acts like a list or array, so can be used with for.

controlling input:

  • using <<>
  • using <>

Thursday, 19 April 2007

STDIN

yesterday, with Ye_Yuan together to try to work out how to decrypt by most stupid way.. however, we find it is impossible to guess this passward, because it need many year. however, it help me to over some UNIX problem.
first is that, I can write script to using STDIN instand of type in by hand. for example, there is a command: smb -U username password servicename. it can lead us into the windows share dirve on Linux service platform. however, when we get into this sharedrive, we need to type command into this program, which means we are in this program. but how can I use script to execute command in sequence? using STDIN. there are two ways, first is like this to write in script:
  1. smb -U zliybsj2 $1 //10.2.1.21/Central_Application_Center <<>
  2. ls
  3. exit
  4. EOF

first, script will using $1 as possward to login Central_Application_Center, then input ls, run it and exit, run again and finish to goto the next command. here EOF is a labell.

another way to write is creating another file, such as com1, we write what we want to do after we get into Central_Application_Center. so, as follow:

  1. smb -U zliybsj2 $1 //10.2.1.21/Central_Application_Center <>

in com1:

  1. ls
  2. exit

There is another way to test when a script or program is runing well by using returning number. as follow:

  1. succ=0
  2. smb -U zliybsj2 $1 //10.2.1.21/Central_Application_Center <>
  3. if [ succ -ed $? ]; then
  4. echo running_well
  5. else
  6. echo some_mistakes_happened
  7. fi

here, $? stands for the retunring number of last program. so if we can complete the left part, such as however to create a pasward, the do this loop to guess, this is the most stupid way to decrypt, if for us time is not a problem. just a joking.

awk

what does awk do:

  1. deal with text file which is thought of as being made up of records and fields. we can write programing by awk to do anything we want.
  2. we can:execute UNIX command from within a script; process the output from UNIX commands; work with multiple input streams; define functions.
  3. we can combined with sed and shell scripting. compared: shell is very easy and quick to write, but lacks functionality. sed, awk, and shell are designed to be integrated.

invoke:

  1. awk [options] 'script' var=value file(s)
  2. awk [options] -f scriptfile var=value file(s) : we can have more than one -f scriptfile.
assigning values to variables can be:

  1. a literal: awk -f scriptFile count=5
  2. a shell variable: awk -f scriptFile count=$count
  3. A command substitution: awk -f scriptFile count=`who wc-l`

set filed seperator:

  1. using -F
  2. one line can be sperated into different filed and can be refered by variables $1, $2 etc. $0 means the whole record.

awk script consist of patterns and procedure:

  1. a pattern can be : /regular expression/, eg /^...:/ or relational expression, eg $1=="gdm". ~ means match, !~ means don't match, eg awk -F: '$1 ~ /.dm.*/ {print $0}' /etc/passwd. BEGIN specifies procedure to take place before the first input line is processed, END as well, eg awk ‘BEGIN {print “Version 1.0”}’ dataFile. pattern missing, the procedure applies all lines
  2. procedure is arround by {} and seperated by newlines or semi-colons. can be: commands, functions and veriable assignment. procedure missing, printed all lines matched by pattern.

commands used with procedures: 5 types

  1. Assignments of variables or arrays
  2. Commands that print
  3. Built-in functions
  4. Control-flow commands
  5. User-defined functions (in nawk only)


awk Built-in Variables:

  1. FILENAME - current filename
  2. FS - Field separator
  3. NF - Number of fields in current record
  4. NR - Number of current record
  5. RS - Record separator
  6. $0 - Entire input record
  7. $n - nth field in current record

awk operators: $_++_ --_ +_-_!_*_/_%_<_<=_>=_>_!=_==_~_!~_in_$$__?:_=_+=_-+_*=_/=_%=

two ways to usingarrays in awk:

  1. in an assignment statement: myArray[i]++
  2. split() function : n=splict(input,words," ") : splict this input by " "(whitespace) into words.

functions in awk: works in the same way as java: calling a function, no sapce between function name and left bracket.

Tuesday, 17 April 2007

sed

introduction:

before this we have two method to deal with text. one is to search by using grep, however we can only show the orgainal text on screan, no modify; the other is to edit using emacs, however we need to open a new window, and all behaviour will be record which means the orgainal one can be changed easly. now, we have another one named sed which can combine both advantages.


character:

  1. work on terminal as command, so will not need to open a new window.
  2. deal with file stored in your computer or online.
  3. it is a lightweight stream editor, so will not using too much memoy, the result will show on scream as stdout
  4. Sed works by performing any number of user-specified editing operations ("commands") on the input data. Sed is line-based, so the commands are performed on each line in order. And, sed writes its results to standard output (stdout); it doesn't modify any input files.

what does sed do:

  1. edit input stream. the orgainal source stay same, only patch match be modified.
  2. produce results on standard output. modifed date can show on scream or pipled.

how does sed work:

  1. make a copy of orginal file. and the left steps are works on this copy not the orgainal one
  2. input the first line into internal bufffer.
  3. act command on this line and print result on scream or file. if there are more than one command being act on one line, it will execute it in sequence, which means the result of former command can be picked by the next command.
  4. input the next line and repeat step 2 and 3 until the while file has been acted.

how to run it from command line:

  1. sed [-n] [-e] 'command' file(s)
  2. sed [-n] -f scriptfile file(s)

formating : using regular excpressions

  1. ^, $, ., *, ?, [], [^]
  2. \{m, n\} :repeat m or more than m times, but no more than n times.
  3. \(, \) : group operator or regin of interest, and alwoys using with \n. often \n appear after \(, \), \n mean nth of \(, \).

sed command syntax: sed [address[,address]] [!]command [arguments]

  1. sed can have 0, 1, or 2 address. and can be line number, symbol or regular expression in slash. no address means applying to each input line. one address meanwhile applying to any line match this address. twp comma_separated address means form one certain line to another certain line. an address followed by ! means DO NOT match this address.
  2. we can put more than one sed element in a command. if first command change the buffer, the will refer to this new stuff.

flag to command:

  1. g: global or all occurences of something
  2. p: print pattern space to stdout if substitution succeddful
  3. n: replace the nth occurence of pattern with replacement text.
  4. w filename: write the pattern space of line that are changed to resultsfile if substitution succcessful.

example:

  1. sed '/^#/d' myfile delecte all line starting with # as comment.
  2. sed '/on/,/5050/d' xinetd.confsed will print the text after 5050. sed -n '/on/,/5050/d' xinetd.confsed will print nothing. sed -n '/on/,/5050/p' xinetd.confsed will print out text between on and 5050. sed '/on/,/5050/p' xinetd.confsed will print the line between on and 5050 each for twice, becasue we first print current line into buffer again, then in 5050, print again.
  3. s/.*// means subtitute all text found for an empty string
  4. who sed -n ‘s/.*(\(.*\))/\1/p’ sort > machines.txt

using different delimiters:

  1. sed tries to match the longest expression!
  2. using non-'>' character: sed -e 's/<[^>]*>//g' UST.html

character classes-posix compliant sed:

  1. sed ‘s/[[:space:]]//g’ myfile
  2. how can we just select but not subtitution or other?



Monday, 16 April 2007