AWK是一种处理文本文件的语言,是一个强大的文本分析工具。
语法
awk [选项参数] 'script' var=value file(s)
或
awk [选项参数] -f scriptfile var=value file(s)
选项与参数
-
-F fs or –field-separator fs 指定分隔符,fs是字符串或正则表达式,如-F,
-
-v var=value or –asign var=value 定义变量
-
-f scripfile or –file scriptfile 从脚本文件中读取awk命令
#首先查看文件的全部内容$ cat file2.txt
1 linux is an os
2 Windows is an os
3 Mac OS is an os
#输出每行的第1、3项内容(默认由空格或tab划分)$ awk '{print $1,$3}' file2.txt
1 is
2 is
3 OS
#将每行以字符'i'划分,输出每行的第1、2项内容$ awk -Fi '{print $1,$2}' file2.txt
l nux
W ndows
Mac OS s an os
#使用内建变量'i'划分,输出每行的第1、2项内容$ awk 'BEGIN{FS="i"} {print $1,$2}' file2.txt
1 l nux
2 W ndows
3 Mac OS s an os
#使用多个分隔符划分,例如i和o(有大小写之分)$ awk -F '[io]' '{print $1,$3,$4}' file2.txt
1 l s an s
2 W ws s an
3 Mac OS s
#给变量赋值,并使用变量$ awk -va=2 -vb=The '{print $1+a,b$2}' file2.txt
3 Thelinux
4 TheWindows
5 TheMac
(如果是要在第二项后面加上‘The’,则这样写‘$2b’)
#使用运算符,输出第一项>=2,且第三项等于"is"的行的前四项内容$ awk '$1>=2 && $3=="is" {print $1,$2,$3,$4}' file2.txt
2 Windows is an
#使用正则表达式,查看包含"os"的行,忽略大小写awk 'BEGIN{IGNORECASE=1} /os/' file2.txt
1 linux is an os
2 Windows is an os
3 Mac OS is an os
awk脚本应当符合以下形式:
BEGIN{ 执行前语句 }
{执行中语句}
END {执行后语句 }
示例:
在工作目录下新建cal.awk脚本,填入以下内容:
BEGIN{
printf "begin\n"
total=0
}
{
printf "Name is %-8s\n",$2
total=total+length
}
END{
printf "total length is %2d\n",total
printf "end"
}
该脚本用于计算文本文件总长度:$ awk -f cal.awk file2.txt
begin
Name is linux
Name is Windows
Name is Mac
total length is 51
end