Awk is a stream type programming language. Awk can edit given text ant provided new text according to instructions. We will look popular usages of Awk in this tutorial. There are alternative awk implementations like below
Awk是一种流类型的编程语言。 Awk可以根据说明编辑给定的文本和提供的新文本。 在本教程中,我们将介绍Awk的流行用法。 还有其他类似的awk实现,如下所示
- Nawk纳克
- Gawk高克
Awk语法(Awk Syntax)
Awk is line oriented so by default provided text is processed line by line. Awk is generally used to search a pattern and make actions against it. We can call this pattern-action language
Awk是面向行的,因此默认情况下,如果文本是逐行处理的。 Awk通常用于搜索模式并对其进行操作。 我们可以称这种模式动作语言
$ awk '/search_pattern/ {action;action;}' file
search_pattern used to find text int file
search_pattern用于查找文本int文件
if search patterns found code between {action} will run.
如果找到搜索模式,则{action}之间的代码将运行。
Awk流 (Awk Flow)
Awk have logic how to process provided text. Awk will follow the steps below.
AWK具有如何处理提供的文本的逻辑。 Awk将遵循以下步骤。
Execute Awk Commands from
BEGIN
block从
BEGIN
块执行Awk命令- Read line from file or standard input从文件或标准输入读取行
- Execute Awk commands on line在线执行Awk命令
- If not end of file go step 2如果不是文件结尾,请执行步骤2
Execute Awk commands from
END
block从
END
块执行Awk命令
示例文本文件(Example Text File)
We will use following text file named fruits
in this tutorial.
在本教程中,我们将使用以下名为fruits
文本文件。
apple 1 good JAN
grape 5 bad DEC
banana 2 good MAR
melon 10 bad JUN
![Example Text File](https://img-blog.csdnimg.cn/img_convert/9f8cfb80d169bfc68439fc87169aa822.png)
逐行打印(Print Line by Line)
We will make an example about how Awk works. In the following example Awk simply read lines from file fruits.txt and write to the standard output. We can see here the logic of Awk a bit.
我们将以Awk的工作方式为例。 在以下示例中,Awk只需从fruits.txt文件中读取行,然后将其写入标准输出即可。 我们可以在这里稍微了解一下Awk的逻辑。
$ awk '{print;}' fruits.txt
![Print Line by Line](https://img-blog.csdnimg.cn/img_convert/382244899bb50bce50ebd3c825247b32.png)
打印匹配行(Print Matched Lines)
Awk usage is not printing files line by line. To create complex usage scenarios there should be some match function. Match is implemented with /
like below by providing text file.
Awk的用法不是逐行打印文件。 要创建复杂的使用场景,应该有一些匹配功能。 通过提供文本文件,使用/
如下所示实现匹配。
$ awk '/bad/' fruits.txt
/bad/
is our search term/bad/
是我们的搜索词