awk分割列-【AWK学习之旅】

---===AWK学习之旅===---

awk 内置分割函数:split,将列按照指定分割符,分割成数组

用法:split(str1,array,"分隔符")

文件内容:

[root@h1 tmp]# cat test.txt
2017-07-25 11:16:10.220 queries client
2017-02-22 12:11:11.880 qeuuadd server

将第二列时间的秒去掉:对第二列处理,以点分割成数组,取第一个元素

[root@h1 tmp]# awk '{split($2,array,".");$2=array[1];print}' test.txt
2017-07-25 11:16:10 queries client
2017-02-22 12:11:11 qeuuadd server

拓展:

处理思想:1.替换列 2.分割列

1.替换列

  (1)awk 直接指定替换

删除将第二列或者替换成任意字符

awk '{$2='';print}' test.txt

awk '{$2='s';print}' test.txt

  (2)内置函数替换gsub

  用法:gsub("被替换字符","替换成的字符","针对的列或行")

[root@h1 tmp]# awk '{gsub("2017","2001",$1);print}' test.txt
2001-07-25 11:16:10.220 queries client
2001-02-22 12:11:11.880 qeuuadd server

2.分割列

内置函数分割:

  (1)split  :分割成数组

  (2)substr  :截取字符串

实例:substr(str1,start,end)

[root@h1 tmp]# awk '{$2=substr($2,3);print}' test.txt
2017-07-25 :16:10.220 queries client
2017-02-22 :11:11.880 qeuuadd server
[root@h1 tmp]# awk '{$2=substr($2,3,6);print}' test.txt
2017-07-25 :16:10 queries client
2017-02-22 :11:11 qeuuadd server

原文地址:https://www.cnblogs.com/cuisi/p/7245722.html