gawk:Unix中原始awk程序的GNU版本,强大之处在于可以写脚本来读取文本行的数据,然后处理并显示数据。
命令格式:gawk options program file
一、gawk基础
1.命令行读取程序脚本
# gawk '{print "hello world"}' //gawk假定脚本是单个文本字符串,须将脚本放到单引号中
hello
hello world
hi
hello world
2.数据字段变量
文本行中发现的数据元素使用$0、$1等来分配变量
$0代表整个文本行
$1代表文本行中的第1个数据字段,$2等依次类推
默认分隔符为空白字符
# gawk '{print $1}' data1
this
# gawk -F: '{print $1}' passwd //使用-F来指定字段分隔符
root
bin
daemon
adm
3.使用多个命令
# echo "this is a test" | gawk '{$4="gawk";print $0}' //使用;号隔开
this is a gawk
4.从文件中读取程序
# cat gawktest
{
text="'s home directory is "
print $1 text $6 //gawk程序中使用变量无需加美元符
}
# gawk -F: -f gawktest passwd
root's home directory is /root
bin's home directory is /bin
daemon's home directory is /sbin
adm's home directory is /var/adm
5.BEGIN与END
# cat beginend
BEGIN { //BEGIN处理数据前运行的脚本
print "userid shell"
print "------ -----"
FS=":" //FS脚本中定义分隔符
}
{
print $1 " " $7 //引号内为制表符,这样输出的结果才能对齐
}
END { //END处理数据后运行的脚本
print "end
命令格式:gawk options program file
一、gawk基础
1.命令行读取程序脚本
# gawk '{print "hello world"}' //gawk假定脚本是单个文本字符串,须将脚本放到单引号中
hello
hello world
hi
hello world
2.数据字段变量
文本行中发现的数据元素使用$0、$1等来分配变量
$0代表整个文本行
$1代表文本行中的第1个数据字段,$2等依次类推
默认分隔符为空白字符
# gawk '{print $1}' data1
this
# gawk -F: '{print $1}' passwd //使用-F来指定字段分隔符
root
bin
daemon
adm
3.使用多个命令
# echo "this is a test" | gawk '{$4="gawk";print $0}' //使用;号隔开
this is a gawk
4.从文件中读取程序
# cat gawktest
{
text="'s home directory is "
print $1 text $6 //gawk程序中使用变量无需加美元符
}
# gawk -F: -f gawktest passwd
root's home directory is /root
bin's home directory is /bin
daemon's home directory is /sbin
adm's home directory is /var/adm
5.BEGIN与END
# cat beginend
BEGIN { //BEGIN处理数据前运行的脚本
print "userid shell"
print "------ -----"
FS=":" //FS脚本中定义分隔符
}
{
print $1 " " $7 //引号内为制表符,这样输出的结果才能对齐
}
END { //END处理数据后运行的脚本
print "end