一、awk命令
- 介绍
awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大。简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行各种分析处理
- 构建操作文本
[hadoop@hadoop001 learn_shell]$ vi test.log
a b c
1 2 3
[hadoop@hadoop001 learn_shell]$ cat test.log | awk '{print $1}'
a
1
[hadoop@hadoop001 learn_shell]$ cat test.log | awk '{print $1,$2}'
a b
1 2
[hadoop@hadoop001 learn_shell]$ cat test.log | awk '{print $1$2}'
ab
12
- 获取第一行数据(
NR:
表示awk开始执行程序后所读取的数据行数)
[hadoop@hadoop001 learn_shell]$ cat test.log | awk 'NR==1 {print}'
a b c
[hadoop@hadoop001 learn_shell]$ cat test.log | awk 'NR==1 {print $1}'
a
[hadoop@hadoop001 learn_shell]$ cat test.log | awk 'NR>1 {print}'
1 2 3
[hadoop@hadoop001 learn_shell]$ vi test.log
a,b,c
1,2,3
[hadoop@hadoop001 learn_shell]$ cat test.log | awk -F "," '{print $1}'
a
1
二、sed命令
- 介绍
sed是Linux下一款功能强大的非交互流式文本编辑器,可以对文本文件进行增、删、改、查等操作,支持按行、按字段、按正则匹配文本内容,灵活方便,特别适合于大文件的编辑
- 构建文本数据
[hadoop@hadoop001 learn_shell]$ vi test.log
a,b,c
1,2,3
[hadoop@hadoop001 learn_shell]$ sed -i 's/a/aa/' test.log
[hadoop@hadoop001 learn_shell]$ cat test.log
aa,b,c
1,2,3
[hadoop@hadoop001 learn_shell]$ sed -i "s/aa/aa'/" test.log
[hadoop@hadoop001 learn_shell]$ cat test.log
aa',b,c
1,2,3
[hadoop@hadoop001 learn_shell]$ sed -i "s/aa'/bbb/" test.log
[hadoop@hadoop001 learn_shell]$ cat test.log
bbb,b,c
1,2,3
[hadoop@hadoop001 learn_shell]$ sed -i "s/b/j/g" test.log
[hadoop@hadoop001 learn_shell]$ cat test.log
jjj,j,c
1,2,3