shell脚本之awk

awk


  • 01.awk介绍

1.awk也是一种编程语言,非常强大。
2.awk用于处理文本文件,或者命令行输入
3.awk是一种动态弱类型的语言,很好的迎合正则。

  • 02.awk匹配正则
[skin@bogon shell]$ cat 1.txt 
hello,one
hello,two
hello,three

#匹配以 'h' 开头,以 ','作为分隔符,并且只打印其第一列
[skin@bogon shell]$ awk -F',' '/^h/{print $1}' 1.txt 
hello
hello
hello

#匹配以 'h' 开头,以 ','作为分隔符,并且倒叙打印其两列
[skin@bogon shell]$ awk -F',' '/^h/{print $2 $1}' 1.txt 
onehello
twohello
threehello

#匹配以 'h' 开头,以 ',' ' ' 作为分隔符,并且打印
[skin@bogon shell]$ echo "hi,tom how are you ?" | awk -F'[, ]' '/^h/{print $3 $4 $5}'
howareyou
  • 03.awk脚本基本格式

基本格式
awk -F'[分隔符]' 'BEGIN{ commands } pattern{ commands } END{ commands }' file

  • -F’ [ 分割符]’
    就是用来将输入流进行切分的,可以回看上述例子

  • 第一步:执行 BEGIN{commands}块
    BEGIN语句块:在awk开始从输入输出流中读取行之前执行,在BEGIN语句块中执行如变量初始化,打印输出表头等操作

  • 第二步:从标准输入或者文件流 ,逐行读取 执行 pattern{commands} 块
    pattern语句块:pattern语句块中的通用命令是最重要的部分,它也是可选的。如果没有提供pattern语句块,则默认执行{ print },即打印每一个读取到的行。{ }类似一个循环体,会对文件中的每一行进行迭代,通常将变量初始化语句放在BEGIN语句块中,将打印结果等语句放在END语句块中

  • 第三步:读至输入流末尾,执行END{commands}块
    END语句块:在awk从输入流中读取完所有的行之后即被执行,比如打印所有行的分析结果这类信息汇总都是在END语句块中完成,它也是一个可选语句块。

#举例:1
# 1.txt文件
[skin@bogon shell]$ cat 1.txt 
1 aaa
2 bbb
3 ccc
4 ddd
5 eee


# test.sh文件
[skin@bogon shell]$ cat test.sh 
#!bin/bash

awk -F' ' 'BEGIN{
    print "start !"
}{
if($1>0)
    {
        print $2
    }
}
END{
    print "end!"
}' 1.txt


# 程序执行结果
[skin@bogon shell]$ sh test.sh 
start !
aaa
bbb
ccc
ddd
eee
end!



#举例:2
# 1.txt文件
[skin@bogon shell]$ cat 1.txt 
1 aaa
2 bbb
3 ccc
4 ddd
5 eee


# test.sh文件
[skin@bogon shell]$ cat test.sh 
#!bin/bash

awk -F' ' 'BEGIN{
    count=0;
}{
    if($1>0)
    {
        count++;
    }
}END{
    print "count="count 
}' 1.txt

#程序执行结果
[skin@bogon shell]$ sh test.sh 
count=5

#举例:3
# test.sh文件
[skin@bogon shell]$ cat test.sh 
#!bin/bash

awk 'BEGIN{
    arr[1]="haha"
    arr[2]="hehe"
    arr[3]="wawa"
    arr[4]="xixi"
    for (i in arr)
        print arr[i]
}'

#程序执行结果
[skin@bogon shell]$ sh test.sh 
xixi
haha
hehe
wawa

这里只写了学习的简单基础,后续会不断修改,如有错误可以私信我,这里表示感谢。

猜你喜欢

转载自blog.csdn.net/SkinWhite/article/details/81213634