AKW

awk 'BEGIN {print "Don\47t Panic!"}'

输出:Don't Panic!

awk '{print }'

等待屏幕输入然后输出,知道ctrl +d停止

awk -f source-file input-file1 input-file2

如果程序比较长的时候。

把下面的程序代码写入任何文件名如davice(就是上面的source-file)

BEGIN { print "Don't Panic!" }  #command in advice
awk -f advice

也可以把advice改成可执行文件,然后直接运行不需要awk -f advice

chmod +x advice
./advice
awk 'BEGIN { print "Don\47t Panic!" }'  #同上面

使用awk编程

#! /usr/bin/awk -f
BEGIN { print "Don't Panic!" }

awk的注释comment以#开头,不要把#comment内容放在单引号内

awk ' {print "hello"}    # let's be cute'
error - can't open file

即使在“let's”中的单引号前面加上backslash(反斜杠)也是error因为在shell中先匹配first tow quotes,因此第三个单引号出现后shell会提示(prompts)等待第二个单引号,所以在结束引号字符串的过程报错。

在shell中使用比较短或者中长awk程序时候,使用单引号把awk命令包含在内。在shell的脚本里也是可以的。

awk 'program text'   input-file1 input-file2

null or empty string:是指character data没有value,在awk中写成""。在shell中可以用单引号或者双引号表示。

$echo ""

引号的用法:

  1. 被引用的部分可以连接未使用quote或者使用quote的items。 shell把所有的都放入一个参数中。
  2. 在single charater前有backslash表示quote这个character,shell处理时会去掉backslash。
  3. 单引号protect 起始引号和结束引号中的everything,shell 不会解释引用中的内容,直接传递给command。在有引号的内容中不可以再嵌入(embed)单引号
  4. 双引号 protect 大部分的内容(在引号内的),另外就是在使用双引号时候,特殊的字符串需要避免使用,或者在其前面加上backslash,eg:'$','~','\','"'
awk 'BEGIN   {  print "Don\47t Panic!"}'  
awk  "BEGIN { print \"Don't Panic!\"  }"   # the same as previous

在双引号中单引号不是特殊字符串。

要正确的使用null string

akw -F ""  ' program' files #correct
akw -F""  ' program' files   #wrong

mixing quotes

akw  'BEGIN  {  print " Here is a single quote <' " ' " ' >"  }'
output: Here is a single quote <'>
awk 'BEGIN { print "Here is a single quote <'\''>" }'  # same as above
output: Here is a single quote <'>
awk "BEGIN { print \"Here is a single quote <'>\"}"  # also the same
akw ' BEGIN { print "Here is a single quote <\47>}'  # octal八进制避免
output: Here is a single quote <'>
akw ' BEGIN { print "Here is a single quote <\42>}'
output: Here is a single quote <">
awk -v sq=" ' " 'BEGIN { print "Here is a single quote <"sq">"}'
output: Here is a single quote <'>

实例:file marks.txt content

1)Amit Physics 80

2)Rahul Maths 90

3)Shyam Biology 87

awk '{  print $3 "\t"   $4} '  marks.txt  #output column 3 and 4
awk '{  print $4 "\t"   $3} '  marks.txt  # output column 4 and 3

awk '/a/ {print $0}' marks.txt  #$0输出整行,/a/是匹配a
输出: 2)Rahul      Maths     90
       3)Shyam    Biology     87
awk '/a/ {print $3 "\t"  $4}' marks.txt
输出:  90 Maths
       87 Biology
awk '/a/{++cnt} END {print "Count = ",cnt}' marks.txt
output: Count=2
awk 'length($0) >18' marks.txt #输出字符串超过18个的记录

akw的内置变量

awk 'BEGIN {print  "Arguments =", ARGC}'  One Two Three Four
Arguments=5
因为数组的索引是0到ARGC-1
awk 'BEGIN { for(i=0;i<argc-1;i++)
   {printf " ARGV[%d]=%s\n",i,ARGV[i]}
          }' one two three four

ARGC命令行参数的个数,ARGV表示命令行输入参数的数组,索引值0到ARGC-1,FILENAME文件名字

results matching ""

    No results matching ""