<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>awk | 酷 壳 - CoolShell</title>
	<atom:link href="https://coolshell.cn/tag/awk/feed" rel="self" type="application/rss+xml" />
	<link>https://coolshell.cn</link>
	<description>享受编程和技术所带来的快乐 - Coding Your Ambition</description>
	<lastBuildDate>Sun, 17 Feb 2013 14:12:39 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.2</generator>
	<item>
		<title>AWK 简明教程</title>
		<link>https://coolshell.cn/articles/9070.html</link>
					<comments>https://coolshell.cn/articles/9070.html#comments</comments>
		
		<dc:creator><![CDATA[陈皓]]></dc:creator>
		<pubDate>Sun, 17 Feb 2013 00:38:29 +0000</pubDate>
				<category><![CDATA[Unix/Linux]]></category>
		<category><![CDATA[杂项资源]]></category>
		<category><![CDATA[编程工具]]></category>
		<category><![CDATA[awk]]></category>
		<category><![CDATA[gawk]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Shell]]></category>
		<category><![CDATA[Unix]]></category>
		<guid isPermaLink="false">http://coolshell.cn/?p=9070</guid>

					<description><![CDATA[<p>有一些网友看了前两天的《Linux下应该知道的技巧》希望我能教教他们用awk和sed，所以，出现了这篇文章。我估计这些80后的年轻朋友可能对awk/sed这类上...</p>
<p class="read-more"><a class="btn btn-default" href="https://coolshell.cn/articles/9070.html"> Read More<span class="screen-reader-text">  Read More</span></a></p>
The post <a href="https://coolshell.cn/articles/9070.html">AWK 简明教程</a> first appeared on <a href="https://coolshell.cn">酷 壳 - CoolShell</a>.]]></description>
										<content:encoded><![CDATA[<p><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3415450859608158"
     crossorigin="anonymous"></script><img decoding="async" loading="lazy" class="alignright size-full wp-image-9093" alt="" src="https://coolshell.cn/wp-content/uploads/2013/02/awk.jpg" width="350" height="279" srcset="https://coolshell.cn/wp-content/uploads/2013/02/awk.jpg 350w, https://coolshell.cn/wp-content/uploads/2013/02/awk-300x239.jpg 300w, https://coolshell.cn/wp-content/uploads/2013/02/awk-339x270.jpg 339w" sizes="(max-width: 350px) 100vw, 350px" />有一些网友看了前两天的《<a title="应该知道的Linux技巧" href="https://coolshell.cn/articles/8883.html" target="_blank">Linux下应该知道的技巧</a>》希望我能教教他们用awk和sed，所以，出现了这篇文章。我估计这些80后的年轻朋友可能对awk/sed这类上古神器有点陌生了，所以需要我这个老家伙来炒炒冷饭。<strong>况且，AWK是贝尔实验室1977年搞出来的文本出现神器，今年是蛇年，是AWK的本命年，而且年纪和我相仿，所以非常有必要为他写篇文章</strong>。</p>
<p>之所以叫AWK是因为其取了三位创始人 <a title="Alfred Aho" href="http://en.wikipedia.org/wiki/Alfred_Aho">Alfred Aho</a>，<a title="Peter J. Weinberger" href="http://en.wikipedia.org/wiki/Peter_J._Weinberger">Peter Weinberger</a>, 和 <a title="Brian Kernighan" href="http://en.wikipedia.org/wiki/Brian_Kernighan">Brian Kernighan</a> 的Family Name的首字符。要学AWK，就得提一提AWK的一本相当经典的书《<a href="http://plan9.bell-labs.com/cm/cs/awkbook/" rel="nofollow">The AWK Programming Language</a>》，它在<a href="http://book.douban.com/subject/1876898/" target="_blank">豆瓣上的评分</a>是9.4分！在<a href="http://www.amazon.cn/mn/detailApp/?asin=020107981X" target="_blank">亚马逊上居然卖1022.30元</a>。</p>
<p>我在这里的教程并不想面面俱到，本文和我之前的<a title="Go 语言简介（上）— 语法" href="https://coolshell.cn/articles/8460.html" target="_blank">Go语言简介</a>一样，全是示例，基本无废话。</p>
<p><strong>我只想达到两个目的：</strong></p>
<p style="text-align: left; padding-left: 30px;"><strong>1）你可以在乘坐公交地铁上下班，或是在坐马桶拉大便时读完（保证是一泡大便的工夫）。</strong></p>
<p style="text-align: left; padding-left: 30px;"><strong>2）我只想让这篇博文像一个火辣的脱衣舞女挑起你的兴趣，然后还要你自己去下工夫去撸。</strong></p>
<p>废话少说，我们开始脱吧（注：这里只是topless）。</p>
<h4>起步上台</h4>
<p>我从netstat命令中提取了如下信息作为用例：</p>
<p><span id="more-9070"></span></p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW">$ cat netstat.txt
Proto Recv-Q Send-Q Local-Address          Foreign-Address             State
tcp        0      0 0.0.0.0:3306           0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:80             0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:9000         0.0.0.0:*                   LISTEN
tcp        0      0 coolshell.cn:80        124.205.5.146:18245         TIME_WAIT
tcp        0      0 coolshell.cn:80        61.140.101.185:37538        FIN_WAIT2
tcp        0      0 coolshell.cn:80        110.194.134.189:1032        ESTABLISHED
tcp        0      0 coolshell.cn:80        123.169.124.111:49809       ESTABLISHED
tcp        0      0 coolshell.cn:80        116.234.127.77:11502        FIN_WAIT2
tcp        0      0 coolshell.cn:80        123.169.124.111:49829       ESTABLISHED
tcp        0      0 coolshell.cn:80        183.60.215.36:36970         TIME_WAIT
tcp        0   4166 coolshell.cn:80        61.148.242.38:30901         ESTABLISHED
tcp        0      1 coolshell.cn:80        124.152.181.209:26825       FIN_WAIT1
tcp        0      0 coolshell.cn:80        110.194.134.189:4796        ESTABLISHED
tcp        0      0 coolshell.cn:80        183.60.212.163:51082        TIME_WAIT
tcp        0      1 coolshell.cn:80        208.115.113.92:50601        LAST_ACK
tcp        0      0 coolshell.cn:80        123.169.124.111:49840       ESTABLISHED
tcp        0      0 coolshell.cn:80        117.136.20.85:50025         FIN_WAIT2
tcp        0      0 :::22                  :::*                        LISTEN
</pre>
<p>下面是最简单最常用的awk示例，其输出第1列和第4例，</p>
<ul>
<li>其中单引号中的被大括号括着的就是awk的语句，注意，其只能被单引号包含。</li>
<li>其中的$1..$n表示第几例。注：$0表示整个行。</li>
</ul>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;{print $1, $4}&#039; netstat.txt
Proto Local-Address
tcp 0.0.0.0:3306
tcp 0.0.0.0:80
tcp 127.0.0.1:9000
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp coolshell.cn:80
tcp :::22</pre>
<p>我们再来看看awk的格式化输出，和C语言的printf没什么两样：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;{printf &quot;%-8s %-8s %-8s %-18s %-22s %-15s\n&quot;,$1,$2,$3,$4,$5,$6}&#039; netstat.txt
Proto    Recv-Q   Send-Q   Local-Address      Foreign-Address        State
tcp      0        0        0.0.0.0:3306       0.0.0.0:*              LISTEN
tcp      0        0        0.0.0.0:80         0.0.0.0:*              LISTEN
tcp      0        0        127.0.0.1:9000     0.0.0.0:*              LISTEN
tcp      0        0        coolshell.cn:80    124.205.5.146:18245    TIME_WAIT
tcp      0        0        coolshell.cn:80    61.140.101.185:37538   FIN_WAIT2
tcp      0        0        coolshell.cn:80    110.194.134.189:1032   ESTABLISHED
tcp      0        0        coolshell.cn:80    123.169.124.111:49809  ESTABLISHED
tcp      0        0        coolshell.cn:80    116.234.127.77:11502   FIN_WAIT2
tcp      0        0        coolshell.cn:80    123.169.124.111:49829  ESTABLISHED
tcp      0        0        coolshell.cn:80    183.60.215.36:36970    TIME_WAIT
tcp      0        4166     coolshell.cn:80    61.148.242.38:30901    ESTABLISHED
tcp      0        1        coolshell.cn:80    124.152.181.209:26825  FIN_WAIT1
tcp      0        0        coolshell.cn:80    110.194.134.189:4796   ESTABLISHED
tcp      0        0        coolshell.cn:80    183.60.212.163:51082   TIME_WAIT
tcp      0        1        coolshell.cn:80    208.115.113.92:50601   LAST_ACK
tcp      0        0        coolshell.cn:80    123.169.124.111:49840  ESTABLISHED
tcp      0        0        coolshell.cn:80    117.136.20.85:50025    FIN_WAIT2
tcp      0        0        :::22              :::*                   LISTEN</pre>
<h4>脱掉外套</h4>
<h5>过滤记录</h5>
<p>我们再来看看如何过滤记录（下面过滤条件为：第三列的值为0 &amp;&amp; 第6列的值为LISTEN）</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;$3==0 &amp;&amp; $6==&quot;LISTEN&quot; &#039; netstat.txt
tcp        0      0 0.0.0.0:3306               0.0.0.0:*              LISTEN
tcp        0      0 0.0.0.0:80                 0.0.0.0:*              LISTEN
tcp        0      0 127.0.0.1:9000             0.0.0.0:*              LISTEN
tcp        0      0 :::22                      :::*                   LISTEN</pre>
<p>其中的“==”为比较运算符。其他比较运算符：!=, &gt;, &lt;, &gt;=, &lt;=</p>
<p>我们来看看各种过滤记录的方式：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039; $3&gt;0 {print $0}&#039; netstat.txt
Proto Recv-Q Send-Q Local-Address          Foreign-Address             State
tcp        0   4166 coolshell.cn:80        61.148.242.38:30901         ESTABLISHED
tcp        0      1 coolshell.cn:80        124.152.181.209:26825       FIN_WAIT1
tcp        0      1 coolshell.cn:80        208.115.113.92:50601        LAST_ACK</pre>
<p>如果我们需要表头的话，我们可以引入内建变量NR：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;$3==0 &amp;&amp; $6==&quot;LISTEN&quot; || NR==1 &#039; netstat.txt
Proto Recv-Q Send-Q Local-Address          Foreign-Address             State
tcp        0      0 0.0.0.0:3306           0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:80             0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:9000         0.0.0.0:*                   LISTEN
tcp        0      0 :::22                  :::*                        LISTEN</pre>
<p>再加上格式化输出：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;$3==0 &amp;&amp; $6==&quot;LISTEN&quot; || NR==1 {printf &quot;%-20s %-20s %s\n&quot;,$4,$5,$6}&#039; netstat.txt
Local-Address        Foreign-Address      State
0.0.0.0:3306         0.0.0.0:*            LISTEN
0.0.0.0:80           0.0.0.0:*            LISTEN
127.0.0.1:9000       0.0.0.0:*            LISTEN
:::22                :::*                 LISTEN</pre>
<h5><strong>内建变量</strong></h5>
<p>说到了内建变量，我们可以来看看awk的一些内建变量：</p>
<table border="0" cellspacing="1" cellpadding="4">
<tbody>
<tr>
<td bgcolor="#ffffff">$0</td>
<td bgcolor="#ffffff">当前记录（这个变量中存放着整个行的内容）</td>
</tr>
<tr>
<td bgcolor="#ffffff">$1~$n</td>
<td bgcolor="#ffffff">当前记录的第n个字段，字段间由FS分隔</td>
</tr>
<tr>
<td bgcolor="#ffffff">FS</td>
<td bgcolor="#ffffff">输入字段分隔符 默认是空格或Tab</td>
</tr>
<tr>
<td bgcolor="#ffffff">NF</td>
<td bgcolor="#ffffff">当前记录中的字段个数，就是有多少列</td>
</tr>
<tr>
<td bgcolor="#ffffff">NR</td>
<td bgcolor="#ffffff">已经读出的记录数，就是行号，从1开始，如果有多个文件话，这个值也是不断累加中。</td>
</tr>
<tr>
<td bgcolor="#ffffff">FNR</td>
<td bgcolor="#ffffff">当前记录数，与NR不同的是，这个值会是各个文件自己的行号</td>
</tr>
<tr>
<td bgcolor="#ffffff">RS</td>
<td bgcolor="#ffffff">输入的记录分隔符， 默认为换行符</td>
</tr>
<tr>
<td bgcolor="#ffffff">OFS</td>
<td bgcolor="#ffffff">输出字段分隔符， 默认也是空格</td>
</tr>
<tr>
<td bgcolor="#ffffff">ORS</td>
<td bgcolor="#ffffff">输出的记录分隔符，默认为换行符</td>
</tr>
<tr>
<td bgcolor="#ffffff">FILENAME</td>
<td bgcolor="#ffffff">当前输入文件的名字</td>
</tr>
</tbody>
</table>
<p>怎么使用呢，比如：我们如果要输出行号：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;$3==0 &amp;&amp; $6==&quot;ESTABLISHED&quot; || NR==1 {printf &quot;%02s %s %-20s %-20s %s\n&quot;,NR, FNR, $4,$5,$6}&#039; netstat.txt
01 1 Local-Address        Foreign-Address      State
07 7 coolshell.cn:80      110.194.134.189:1032 ESTABLISHED
08 8 coolshell.cn:80      123.169.124.111:49809 ESTABLISHED
10 10 coolshell.cn:80      123.169.124.111:49829 ESTABLISHED
14 14 coolshell.cn:80      110.194.134.189:4796 ESTABLISHED
17 17 coolshell.cn:80      123.169.124.111:49840 ESTABLISHED</pre>
<h5><strong>指定分隔符</strong></h5>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$  awk  &#039;BEGIN{FS=&quot;:&quot;} {print $1,$3,$6}&#039; /etc/passwd
root 0 /root
bin 1 /bin
daemon 2 /sbin
adm 3 /var/adm
lp 4 /var/spool/lpd
sync 5 /sbin
shutdown 6 /sbin
halt 7 /sbin</pre>
<p>上面的命令也等价于：（-F的意思就是指定分隔符）</p>
<p><code data-enlighter-language="shell" class="EnlighterJSRAW">$ awk  -F: &#039;{print $1,$3,$6}&#039; /etc/passwd</code></p>
<p>注：如果你要指定多个分隔符，你可以这样来：</p>
<p><code data-enlighter-language="shell" class="EnlighterJSRAW">awk -F &#039;[;:]&#039;</code></p>
<p>再来看一个以\t作为分隔符输出的例子（下面使用了/etc/passwd文件，这个文件是以:分隔的）：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk  -F: &#039;{print $1,$3,$6}&#039; OFS=&quot;\t&quot; /etc/passwd
root    0       /root
bin     1       /bin
daemon  2       /sbin
adm     3       /var/adm
lp      4       /var/spool/lpd
sync    5       /sbin</pre>
<h4>脱掉衬衫</h4>
<h5>字符串匹配</h5>
<p>我们再来看几个字符串匹配的示例：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1,8">$ awk &#039;$6 ~ /FIN/ || NR==1 {print NR,$4,$5,$6}&#039; OFS=&quot;\t&quot; netstat.txt
1       Local-Address   Foreign-Address State
6       coolshell.cn:80 61.140.101.185:37538    FIN_WAIT2
9       coolshell.cn:80 116.234.127.77:11502    FIN_WAIT2
13      coolshell.cn:80 124.152.181.209:26825   FIN_WAIT1
18      coolshell.cn:80 117.136.20.85:50025     FIN_WAIT2

$ $ awk &#039;$6 ~ /WAIT/ || NR==1 {print NR,$4,$5,$6}&#039; OFS=&quot;\t&quot; netstat.txt
1       Local-Address   Foreign-Address State
5       coolshell.cn:80 124.205.5.146:18245     TIME_WAIT
6       coolshell.cn:80 61.140.101.185:37538    FIN_WAIT2
9       coolshell.cn:80 116.234.127.77:11502    FIN_WAIT2
11      coolshell.cn:80 183.60.215.36:36970     TIME_WAIT
13      coolshell.cn:80 124.152.181.209:26825   FIN_WAIT1
15      coolshell.cn:80 183.60.212.163:51082    TIME_WAIT
18      coolshell.cn:80 117.136.20.85:50025     FIN_WAIT2</pre>
<p>上面的第一个示例匹配FIN状态， 第二个示例匹配WAIT字样的状态。其实 ~ 表示模式开始。/ /中是模式。这就是一个正则表达式的匹配。</p>
<p>其实awk可以像grep一样的去匹配第一行，就像这样：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;/LISTEN/&#039; netstat.txt
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN
tcp        0      0 :::22                   :::*                    LISTEN</pre>
<p>我们可以使用 “/FIN|TIME/” 来匹配 FIN 或者 TIME :</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;$6 ~ /FIN|TIME/ || NR==1 {print NR,$4,$5,$6}&#039; OFS=&quot;\t&quot; netstat.txt
1       Local-Address   Foreign-Address State
5       coolshell.cn:80 124.205.5.146:18245     TIME_WAIT
6       coolshell.cn:80 61.140.101.185:37538    FIN_WAIT2
9       coolshell.cn:80 116.234.127.77:11502    FIN_WAIT2
11      coolshell.cn:80 183.60.215.36:36970     TIME_WAIT
13      coolshell.cn:80 124.152.181.209:26825   FIN_WAIT1
15      coolshell.cn:80 183.60.212.163:51082    TIME_WAIT
18      coolshell.cn:80 117.136.20.85:50025     FIN_WAIT2</pre>
<p>再来看看模式取反的例子：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;$6 !~ /WAIT/ || NR==1 {print NR,$4,$5,$6}&#039; OFS=&quot;\t&quot; netstat.txt
1       Local-Address   Foreign-Address State
2       0.0.0.0:3306    0.0.0.0:*       LISTEN
3       0.0.0.0:80      0.0.0.0:*       LISTEN
4       127.0.0.1:9000  0.0.0.0:*       LISTEN
7       coolshell.cn:80 110.194.134.189:1032    ESTABLISHED
8       coolshell.cn:80 123.169.124.111:49809   ESTABLISHED
10      coolshell.cn:80 123.169.124.111:49829   ESTABLISHED
12      coolshell.cn:80 61.148.242.38:30901     ESTABLISHED
14      coolshell.cn:80 110.194.134.189:4796    ESTABLISHED
16      coolshell.cn:80 208.115.113.92:50601    LAST_ACK
17      coolshell.cn:80 123.169.124.111:49840   ESTABLISHED
19      :::22   :::*    LISTEN</pre>
<p>或是：</p>
<p><code data-enlighter-language="shell" class="EnlighterJSRAW">awk &#039;!/WAIT/&#039; netstat.txt</code></p>
<p><strong>折分文件</strong></p>
<p>awk拆分文件很简单，使用重定向就好了。下面这个例子，是按第6例分隔文件，相当的简单（其中的NR!=1表示不处理表头）。</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;NR!=1{print &gt; $6}&#039; netstat.txt

$ ls
ESTABLISHED  FIN_WAIT1  FIN_WAIT2  LAST_ACK  LISTEN  netstat.txt  TIME_WAIT

$ cat ESTABLISHED
tcp        0      0 coolshell.cn:80        110.194.134.189:1032        ESTABLISHED
tcp        0      0 coolshell.cn:80        123.169.124.111:49809       ESTABLISHED
tcp        0      0 coolshell.cn:80        123.169.124.111:49829       ESTABLISHED
tcp        0   4166 coolshell.cn:80        61.148.242.38:30901         ESTABLISHED
tcp        0      0 coolshell.cn:80        110.194.134.189:4796        ESTABLISHED
tcp        0      0 coolshell.cn:80        123.169.124.111:49840       ESTABLISHED

$ cat FIN_WAIT1
tcp        0      1 coolshell.cn:80        124.152.181.209:26825       FIN_WAIT1

$ cat FIN_WAIT2
tcp        0      0 coolshell.cn:80        61.140.101.185:37538        FIN_WAIT2
tcp        0      0 coolshell.cn:80        116.234.127.77:11502        FIN_WAIT2
tcp        0      0 coolshell.cn:80        117.136.20.85:50025         FIN_WAIT2

$ cat LAST_ACK
tcp        0      1 coolshell.cn:80        208.115.113.92:50601        LAST_ACK

$ cat LISTEN
tcp        0      0 0.0.0.0:3306           0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:80             0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:9000         0.0.0.0:*                   LISTEN
tcp        0      0 :::22                  :::*                        LISTEN

$ cat TIME_WAIT
tcp        0      0 coolshell.cn:80        124.205.5.146:18245         TIME_WAIT
tcp        0      0 coolshell.cn:80        183.60.215.36:36970         TIME_WAIT
tcp        0      0 coolshell.cn:80        183.60.212.163:51082        TIME_WAIT</pre>
<p>你也可以把指定的列输出到文件：</p>
<p><code data-enlighter-language="shell" class="EnlighterJSRAW">awk &#039;NR!=1{print $4,$5 &gt; $6}&#039; netstat.txt</code></p>
<p>再复杂一点：（注意其中的if-else-if语句，可见awk其实是个脚本解释器）</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1,2,3">$ awk &#039;NR!=1{if($6 ~ /TIME|ESTABLISHED/) print &gt; &quot;1.txt&quot;;
else if($6 ~ /LISTEN/) print &gt; &quot;2.txt&quot;;
else print &gt; &quot;3.txt&quot; }&#039; netstat.txt

$ ls ?.txt
1.txt  2.txt  3.txt

$ cat 1.txt
tcp        0      0 coolshell.cn:80        124.205.5.146:18245         TIME_WAIT
tcp        0      0 coolshell.cn:80        110.194.134.189:1032        ESTABLISHED
tcp        0      0 coolshell.cn:80        123.169.124.111:49809       ESTABLISHED
tcp        0      0 coolshell.cn:80        123.169.124.111:49829       ESTABLISHED
tcp        0      0 coolshell.cn:80        183.60.215.36:36970         TIME_WAIT
tcp        0   4166 coolshell.cn:80        61.148.242.38:30901         ESTABLISHED
tcp        0      0 coolshell.cn:80        110.194.134.189:4796        ESTABLISHED
tcp        0      0 coolshell.cn:80        183.60.212.163:51082        TIME_WAIT
tcp        0      0 coolshell.cn:80        123.169.124.111:49840       ESTABLISHED

$ cat 2.txt
tcp        0      0 0.0.0.0:3306           0.0.0.0:*                   LISTEN
tcp        0      0 0.0.0.0:80             0.0.0.0:*                   LISTEN
tcp        0      0 127.0.0.1:9000         0.0.0.0:*                   LISTEN
tcp        0      0 :::22                  :::*                        LISTEN

$ cat 3.txt
tcp        0      0 coolshell.cn:80        61.140.101.185:37538        FIN_WAIT2
tcp        0      0 coolshell.cn:80        116.234.127.77:11502        FIN_WAIT2
tcp        0      1 coolshell.cn:80        124.152.181.209:26825       FIN_WAIT1
tcp        0      1 coolshell.cn:80        208.115.113.92:50601        LAST_ACK
tcp        0      0 coolshell.cn:80        117.136.20.85:50025         FIN_WAIT2</pre>
<h5>统计</h5>
<p>下面的命令计算所有的C文件，CPP文件和H文件的文件大小总和。</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW">$ ls -l  *.cpp *.c *.h | awk &#039;{sum+=$5} END {print sum}&#039;
2511401</pre>
<p>我们再来看一个统计各个connection状态的用法：（我们可以看到一些编程的影子了，大家都是程序员我就不解释了。注意其中的数组的用法）</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ awk &#039;NR!=1{a[$6]++;} END {for (i in a) print i &quot;, &quot; a[i];}&#039; netstat.txt
TIME_WAIT, 3
FIN_WAIT1, 1
ESTABLISHED, 6
FIN_WAIT2, 3
LAST_ACK, 1
LISTEN, 4</pre>
<p>再来看看统计每个用户的进程的占了多少内存（注：sum的RSS那一列）</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="1">$ ps aux | awk &#039;NR!=1{a[$1]+=$6;} END { for(i in a) print i &quot;, &quot; a[i]&quot;KB&quot;;}&#039;
dbus, 540KB
mysql, 99928KB
www, 3264924KB
root, 63644KB
hchen, 6020KB</pre>
<h4>脱掉内衣</h4>
<h5>awk脚本</h5>
<p>在上面我们可以看到一个END关键字。END的意思是“处理完所有的行的标识”，即然说到了END就有必要介绍一下BEGIN，这两个关键字意味着执行前和执行后的意思，语法如下：</p>
<ul>
<li>BEGIN{ 这里面放的是执行前的语句 }</li>
<li>END {这里面放的是处理完所有的行后要执行的语句 }</li>
<li>{这里面放的是处理每一行时要执行的语句}</li>
</ul>
<p>为了说清楚这个事，我们来看看下面的示例：</p>
<p>假设有这么一个文件（学生成绩表）：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW">$ cat score.txt
Marry   2143 78 84 77
Jack    2321 66 78 45
Tom     2122 48 77 71
Mike    2537 87 97 95
Bob     2415 40 57 62</pre>
<p>我们的awk脚本如下（我没有写有命令行上是因为命令行上不易读，另外也在介绍另一种用法）：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW">$ cat cal.awk
#!/bin/awk -f
#运行前
BEGIN {
    math = 0
    english = 0
    computer = 0

    printf &quot;NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL\n&quot;
    printf &quot;---------------------------------------------\n&quot;
}
#运行中
{
    math+=$3
    english+=$4
    computer+=$5
    printf &quot;%-6s %-6s %4d %8d %8d %8d\n&quot;, $1, $2, $3,$4,$5, $3+$4+$5
}
#运行后
END {
    printf &quot;---------------------------------------------\n&quot;
    printf &quot;  TOTAL:%10d %8d %8d \n&quot;, math, english, computer
    printf &quot;AVERAGE:%10.2f %8.2f %8.2f\n&quot;, math/NR, english/NR, computer/NR
}</pre>
<p>我们来看一下执行结果：（也可以这样运行 ./cal.awk score.txt）</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW">$ awk -f cal.awk score.txt
NAME    NO.   MATH  ENGLISH  COMPUTER   TOTAL
---------------------------------------------
Marry  2143     78       84       77      239
Jack   2321     66       78       45      189
Tom    2122     48       77       71      196
Mike   2537     87       97       95      279
Bob    2415     40       57       62      159
---------------------------------------------
  TOTAL:       319      393      350
AVERAGE:     63.80    78.60    70.00</pre>
<h5>环境变量</h5>
<p>即然说到了脚本，我们来看看怎么和环境变量交互：（使用-v参数和ENVIRON，使用ENVIRON的环境变量需要export）</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW" data-enlighter-highlight="9">$ x=5

$ y=10
$ export y

$ echo $x $y
5 10

$ awk -v val=$x &#039;{print $1, $2, $3, $4+val, $5+ENVIRON[&quot;y&quot;]}&#039; OFS=&quot;\t&quot; score.txt
Marry   2143    78      89      87
Jack    2321    66      83      55
Tom     2122    48      82      81
Mike    2537    87      102     105
Bob     2415    40      62      72
</pre>
<h4>几个花活</h4>
<p>最后，我们再来看几个小例子：</p>
<pre data-enlighter-language="shell" class="EnlighterJSRAW">#从file文件中找出长度大于80的行
awk &#039;length&gt;80&#039; file

#按连接数查看客户端IP
netstat -ntu | awk &#039;{print $5}&#039; | cut -d: -f1 | sort | uniq -c | sort -nr

#打印99乘法表
seq 9 | sed &#039;H;g&#039; | awk -v RS=&#039;&#039; &#039;{for(i=1;i&lt;=NF;i++)printf(&quot;%dx%d=%d%s&quot;, i, NR, i*NR, i==NR?&quot;\n&quot;:&quot;\t&quot;)}&#039; </pre>
<h4>自己撸吧</h4>
<p>关于其中的一些知识点可以参看<a href="http://www.gnu.org/software/gawk/manual/gawk.html" target="_blank">gawk的手册</a>：</p>
<ul>
<li>内建变量，参看：<a href="http://www.gnu.org/software/gawk/manual/gawk.html#Built_002din-Variables" target="_blank">http://www.gnu.org/software/gawk/manual/gawk.html#Built_002din-Variables</a></li>
<li>流控方面，参看：<a href="http://www.gnu.org/software/gawk/manual/gawk.html#Statements" target="_blank">http://www.gnu.org/software/gawk/manual/gawk.html#Statements</a></li>
<li>内建函数，参看：<a href="http://www.gnu.org/software/gawk/manual/gawk.html#Built_002din" target="_blank">http://www.gnu.org/software/gawk/manual/gawk.html#Built_002din</a></li>
<li>正则表达式，参看：<a href="http://www.gnu.org/software/gawk/manual/gawk.html#Regexp" target="_blank">http://www.gnu.org/software/gawk/manual/gawk.html#Regexp</a></li>
</ul>
<p>（全文完）<!--



<p align="center"><a href= target=_blank><img decoding="async" src=""></a></p>





<p align="center"><img decoding="async" src="https://coolshell.cn/wp-content/uploads/2020/03/coolshell.weixin.jpg"> <img decoding="async" loading="lazy" src="https://coolshell.cn/wp-content/uploads/2020/03/coolshell.mini_.jpg" width="300" height="300"> <br />关注CoolShell微信公众账号和微信小程序</p>

 

--></p>
<div style="margin-top: 15px; font-size: 16px;color: #cc0000;">
<p align="center"><strong>（转载本站文章请注明作者和出处 <a href="https://coolshell.cn/">酷 壳 &#8211; CoolShell</a> ，请勿用于任何商业用途）</strong></p>
</div>

<div class="wp_rp_wrap  wp_rp_vertical_m" id="wp_rp_first"><div class="wp_rp_content"><h3 class="related_post_title">相关文章</h3><ul class="related_post wp_rp"><li ><a href="https://coolshell.cn/articles/8883.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2013/01/linux-bash-300x225-150x150.jpg" alt="应该知道的Linux技巧" width="150" height="150" /></a><a href="https://coolshell.cn/articles/8883.html" class="wp_rp_title">应该知道的Linux技巧</a></li><li ><a href="https://coolshell.cn/articles/8619.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2012/11/shell.01-150x150.png" alt="你可能不知道的Shell" width="150" height="150" /></a><a href="https://coolshell.cn/articles/8619.html" class="wp_rp_title">你可能不知道的Shell</a></li><li ><a href="https://coolshell.cn/articles/19219.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2019/03/linux.ninja_-150x150.png" alt="打造高效的工作环境 &#8211; Shell 篇" width="150" height="150" /></a><a href="https://coolshell.cn/articles/19219.html" class="wp_rp_title">打造高效的工作环境 &#8211; Shell 篇</a></li><li ><a href="https://coolshell.cn/articles/18360.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2018/05/300x262-150x150.jpg" alt="程序员练级攻略（2018)  与我的专栏" width="150" height="150" /></a><a href="https://coolshell.cn/articles/18360.html" class="wp_rp_title">程序员练级攻略（2018)  与我的专栏</a></li><li ><a href="https://coolshell.cn/articles/17998.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2017/07/systemd-1-150x150.jpeg" alt="Linux PID 1 和 Systemd" width="150" height="150" /></a><a href="https://coolshell.cn/articles/17998.html" class="wp_rp_title">Linux PID 1 和 Systemd</a></li><li ><a href="https://coolshell.cn/articles/12103.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2014/11/tux-fork-150x150.gif" alt="vfork 挂掉的一个问题" width="150" height="150" /></a><a href="https://coolshell.cn/articles/12103.html" class="wp_rp_title">vfork 挂掉的一个问题</a></li></ul></div></div>The post <a href="https://coolshell.cn/articles/9070.html">AWK 简明教程</a> first appeared on <a href="https://coolshell.cn">酷 壳 - CoolShell</a>.]]></content:encoded>
					
					<wfw:commentRss>https://coolshell.cn/articles/9070.html/feed</wfw:commentRss>
			<slash:comments>260</slash:comments>
		
		
			</item>
	</channel>
</rss>
