Home  >  Article  >  php教程  >  Detailed explanation of awk command

Detailed explanation of awk command

高洛峰
高洛峰Original
2016-12-12 16:12:161401browse

简单使用:

awk :对于文件中一行行的独处来执行操作 。

awk -F :'{print $1,$4}'   :使用‘:’来分割这一行,把这一行的第一第四个域打印出来 。 

详细介绍:

AWK命令介绍 

awk语言的最基本功能是在文件或字符串中基于指定规则浏览和抽取信息,awk抽取信息后,才能进行其他文本操作,完整的awk脚本通常用来格式化文本文件中的信息

 

1.   调用awk:

 第一种命令行方式,如:

 awk [-Field-separator] 'commands' input-file(s)

 这里commands是真正的awk命令,[-F域分隔符]是可选的,awk默认使用空格分隔,因此如果要浏览域间有空格的文本,不必指定这个选 项,但如果浏览如passwd文件,此文件各域使用冒号作为分隔符,则必须使用-F选项:   awk -F : 'commands' input-file

第二种,将所有awk命令插入一个文件,并使awk程序可执行,然后用awk命令解释器作为脚本的首行,以便通过键入脚本名称来调用它

第三种,将所有awk命令插入一个单独文件,然后调用,如: 

 awk -f awk-script-file input-file

 -f选项指明在文件awk-script-file的awk脚本,input-file是使用awk进行浏览的文件名

 2.   awk脚本:

   awk脚本由各种操作和模式组成,根据分隔符(-F选项),默认为空格,读取的内容依次放置到对应的域中,一行一行记录读取,直到文件尾

 2.1.      模式和动作   

 任何awk语句都是由模式和动作组成,在一个awk脚本中可能有许多语句。模式部分决定动作语句何时触发及触发事件。动作即对数据进行的操作,如果省去模式部分,动作将时刻保持执行状态

     模式可以是任何条件语句或复合语句或正则表达式,模式包含两个特殊字段BEGIN和END,使用BEGIN语句设置计数和打印 头,BEGIN语句使用在任何文本浏览动作之前,之后文本浏览动作依据输入文件开始执行;END语句用来在awk完成文本浏览动作后打印输出文本总数和结 尾状态标志,有动作必须使用{}括起来

     实际动作在大括号{}内指明,常用来做打印动作,但是还有更长的代码如if和循环looping语句及循环退出等,如果不指明采取什么动作,awk默认打印出所有浏览出的记录

 2.2.     域和记录:

 awk执行时,其浏览标记为$1,$2...$n,这种方法称为域标记。使用$1,$3表示参照第1和第3域,注意这里使用逗号分隔域,使用$0表示使用所有域。例如:

 awk '{print $0}' temp.txt > sav.txt

 表示打印所有域并把结果重定向到sav.txt中

 awk '{print $0}' temp.txt|tee sav.txt

  和上例相似,不同的是将在屏幕上显示出来

 awk '{print $1,$4}' temp.txt

    只打印出第1和第4域

 awk 'BEGIN {print "NAME  GRADE\n----"} {print $1"\t"$4}' temp.txt

 表示打信息头,即输入的内容的第一行前加上"NAME  GRADE\n-------------",同时内容以tab分开

 awk 'BEGIN {print "being"} {print $1} END {print "end"}' temp

 同时打印信息头和信息尾

 2.3.     条件操作符:

   =、~匹配正则表达式、!~不匹配正则表达式

     匹配:awk '{if ($4~/ASIMA/) print $0}' temp 表示如果第四个域包含ASIMA,就打印整条

     精确匹配:awk '$3=="48" {print $0}' temp    只打印第3域等于"48"的记录

     不匹配:  awk '$0 !~ /ASIMA/' temp      打印整条不包含ASIMA的记录

     不等于:  awk '$1 != "asima"' temp

     小于:    awk '{if ($1

     设置大小写: awk '/[Gg]reen/' temp      打印整条包含Green,或者green的记录

     任意字符: awk '$1 ~/^...a/' temp    打印第1域中第四个字符是a的记录,符号’^’代表行首,符合’.’代表任意字符

     或关系匹配: awk '$0~/(abc)|(efg)/' temp   使用|时,语句需要括起来

     AND与关系:  awk '{if ( $1=="a" && $2=="b" ) print $0}' temp

     OR或关系:   awk '{if ($1=="a" || $1=="b") print $0}' temp

 

2.4.     Detailed explanation of awk command:

Detailed explanation of awk command

Example: awk 'END {print NR}' temp Print the number of read records at the end

awk '{print NF, NR, $0} END {print FILENAME}' temp

awk '{if (NR> ;0 && $4~/Brown/) print $0}' temp There is at least one record and contains Brown

Another usage of NF: echo $PWD | awk -F/ '{print $NF}' Display the current directory name

2.5. awk operator:

Using operators in awk, basic expressions can be divided into numbers, strings, variables, fields and array elements

Set the input field to the variable name:

awk ' {name=$1;six=$3; if (six=="man") print name " is " six}' temp

Domain value comparison operation:

awk 'BEGIN {BASE="27"} {if ($4

Modify the value of the numerical field: (the original input file will not be changed)

awk '{if ($1=="asima") $6=$6-1;print $1, $6 , $7}' temp

Modify the text field:

awk '{if ($1=="asima) ($1=="desc");print $1}' temp

Only display modification records: (Only display what is needed Yes, differ from the previous command, please note {})

awk '{if ($1=="asima) {$1=="desc";print$1}}' temp

Create a new output domain:

awk ' {$4=$3-$2; print $4}' temp

Statistical column value:

awk '(tot+=$3);END {print tot}' temp will display the content of each column

awk '{(tot+=$3 )};END {print tot}' temp only displays the final result

Add the file lengths:

ls -l|awk '/^[^d]/ {print $9"t"$5} {tot+=$5} END{print "totKB:" tot}'

List only the file name:

ls -l|awk '{print $9}' Normally the file name is the 9th field

2.6. awk built-in string function ; The first position of the Rd Index (s, T) is replaced by S. The first position of the string T in s )                                                                                                                                                                                                                                         out out out out of s

split(s, a, fs) Split s into sequence a on fs

awk 'BEGIN {print split("12#345#6789", myarray, "#")"'

Return 3, and myarray[ 1]="12", myarray[2]="345", myarray[3]="6789"

sprint(fmt, exp) Returns the exp formatted by fmt

sub(r, s) from $0 Replace r with s in the leftmost longest substring (only replace the first matching string encountered)

substr(s, p) Returns the suffix part starting from p in string s

substr(s, p, n) Returns the suffix part starting from p and having a length of n in string s

2.7. Use of printf function:

Character conversion: echo "65" |awk '{printf "%cn", $0} ' Output A

awk 'BEGIN {printf "%fn",999}' Output 999.000000

Formatted output: awk '{printf "%-15s %sn",$1,$3}' temp Change the first domain All displayed left aligned

2.8. Other awk usage:

Passing value to a line of awk command:

awk '{if ($5 who | awk '{ if ($1==user) print $1 " are in " $2 ' user=$LOGNAME using environment variables

awk script command:

Use !/bin/awk -f at the beginning. Without this sentence, the self-contained script will not be executed. Example:

!/bin/awk -f

# all comment lines must start with a hash '#'

# name: student_tot.awk

# to call: student_tot.awk grade.txt

# prints total and average of club student points

# print a header first

BEGIN

{

print "Student Date Member No . Grade Age Points Max"

print "Name Joined Gained Point Available"

print"============================== ==========================="

}

# let's add the scores of points gained

(tot+=$6);

# finished processing now let's print the total and average point

END

{

​​ print "Club student total points:" tot

​​ print "Average Club Student points:" tot/N

}

awk Array:

awk’s basic loop structure

For (element in array) print array[element]

awk 'BEGIN {record="123#456#789";split(record, myarray, "#")}

END { for (i in myarray) {print myarray[i]} }

3.0 Custom statements in awk

1. Conditional judgment statement (if)

if (expression) #if ( Variable in Array )
Statement 1
else
Statement 2

In the format, "Statement 1" can be multiple statements. If you want to facilitate Unix awk judgment and your own reading, you'd better enclose multiple statements with {}. Unix awk branch structure allows nesting, and its format is:

if(expression)

{statement 1}

else if(expression)
{statement 2}
else
{statement 3}

[chengmo @localhost nginx]# awk 'BEGIN{
test=100;
if(test>90)
{
 print "very good";
}
else if(test>60)
{
 print "good";
}
else
{
  print "no pass";
}
}'

very good

You can end each command statement with a ";" sign.

2. Loop statement (while, for, do)

1. while statement

format:

while (expression)

{statement}

example:

[chengmo@localhost nginx]# awk 'BEGIN{
test=100;
total=0;
while(i{
  total+=i;
 i++;
}
print total;
}'
5050

2.for loop

for loop has two formats:

Format 1:

for (variable in array)

{statement}

Example:

[chengmo@localhost nginx]# awk 'BEGIN{
for(k in ENVIRON)
{
 print k"="ENVIRON[k];
}
}'

AWKPATH=.:/usr/share/awk
OLDPWD=/home/web97
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh -askpass
SELINUX_LEVEL_REQUESTED=
SELINUX_ROLE_REQUESTED=
LANG=zh_CN.GB2312

. . . . . .

Explanation: ENVIRON is an awk constant and a sub-typical array.

Format 2:

for (variable; condition; expression)

{statement}

Example:

[chengmo@localhost nginx]# awk 'BEGIN{
total=0;
for(i=0; i{
  total+=i;
}
print total;
}'

5050

3.do loop

Format:

do

{statement}while (condition)

Example:

[chengmo@localhost nginx]# awk 'BEGIN{
total=0;
i=0;
do
{
total+=i;
i++;
}while(iprint total;
}'
5050

The above is the awk flow control statement. From the syntax, you can see that it is the same as the c language. With these statements, many shell programs can actually be handed over to awk, and the performance is very fast.

Detailed explanation of awk command

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:AWK command usageNext article:AWK command usage