linux下awk命令用法

来源:互联网 发布:人工智能自然语言理解 编辑:程序博客网 时间:2024/05/01 23:54

1.awk介绍

       linux下awk命令是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在对数据进行分析时显得尤为强大。简单来说,awk命令就是将输出流逐行导入,以空格为默认分隔符将每行切片,再进行后续的处理。

      awk有3个不同的版本:awk、nawk和gawk,一般使用的是gawk,它是awk的GNU版本。

使用方法:

awk '/parttern/{action}' {filenames}
其中pattern是在数据中查找的内容,为正则表达式,需要使用/号括起来 。而action是指在匹配到内容时所执行的一系列命令。花括号{},不需要再程序中始终出现,但它们用于根据特定的模式对一系列指令进行分组。

以下是awk的命令帮助:

Usage: awk [POSIX or GNU style options] -f progfile [--] file ...Usage: awk [POSIX or GNU style options] [--] 'program' file ...POSIX options:          GNU long options:        -f progfile             --file=progfile        -F fs                   --field-separator=fs        -v var=val              --assign=var=val        -m[fr] val        -W compat               --compat        -W copyleft             --copyleft        -W copyright            --copyright        -W dump-variables[=file]        --dump-variables[=file]        -W exec=file            --exec=file        -W gen-po               --gen-po        -W help                 --help        -W lint[=fatal]         --lint[=fatal]        -W lint-old             --lint-old        -W non-decimal-data     --non-decimal-data        -W profile[=file]       --profile[=file]        -W posix                --posix        -W re-interval          --re-interval        -W source=program-text  --source=program-text        -W traditional          --traditional        -W usage                --usage        -W version              --versionTo report bugs, see node `Bugs' in `gawk.info', which issection `Reporting Problems and Bugs' in the printed version.gawk is a pattern scanning and processing language.By default it reads standard input and writes standard output.Examples:        gawk '{ sum += $1 }; END { print sum }' file        gawk -F: '{ print $1 }' /etc/passwd


2.awk入门例子

1)使用正则匹配查找

ps -ef | awk '/^www/{print $0}' | tail -n 10
以上例子是查找www用户进程的最后10个进程

2)使用命令

cat /etc/passwd | awk -F ':'  '{print $1}'
以上例子是查找当前系统有多少个密码用户,-F是自定义分隔符,{}中是执行代码。awk的工作流程是这样的,读入有'\n'换行符分隔的一条记录,然后将记录按指定与分隔符划分区域(-F '[分隔符]'')。$0表示所有域,$1表示第一个域,如果不指定-F ,默认的分割符是空格或tab键。






0 0
原创粉丝点击