一:cut

1.1 简介

  • cut 的工作就是“剪”,具体的说就是在文件中负责剪切数据用的。
  • cut 命令从文件的每一行剪切字节、字符和字段并将这些字节、字符和字段输出。

1.2 基本用法

  • cut [选项参数] filename
  • 说明:默认分隔符是制表符

1.3 选项参数说明

1.4 案例实操

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[root@hadoop100 shell]# cat cut.txt 
xiao hong
xiao ming
hello world
bei jing
# 按空格切分,取第一列
[root@hadoop100 shell]# cut -d " " -f 1 cut.txt
xiao
xiao
hello
bei
# 按空格切分,取第二列、第三列
[root@hadoop100 shell]# cut -d " " -f 2,3 cut.txt
hong
ming
world
jing
# 切割出 world
[root@hadoop100 shell]# cat cut.txt | grep hello | cut -d " " -f 2
world
# 选取系统 PATH 变量值,第 2 个“:”开始后的所有路径
[root@hadoop100 shell]# echo $PATH | cut -d ":" -f 3-
/usr/sbin:/usr/bin:/root/bin

# 切割出ifconfig中的ip地址
[root@hadoop100 shell]# ifconfig | grep netmask | cut -d " " -f 10
172.16.80.100
127.0.0.1
192.168.122.1

二:awk

2.1 简介

一个强大的文本分析工具,把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再进行分析处理。

2.2 基本语法

  • awk [选项参数] ‘/pattern1/{action1} /pattern2/{action2}…’ filename
  • pattern:表示 awk 在数据中查找的内容,就是匹配模式
  • action:在找到匹配内容时所执行的一系列命令

2.3 选项参数说明

2.4 案例实操

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# passwd 数据的含义
# 用户名:密码(加密过后的):用户 id:组 id:注释:用户家目录:shell 解析器
[root@hadoop100 shell]# cat /etc/passwd | head -3
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

# 搜索 passwd 文件以 root 关键字开头的所有行,并输出该行的第 7 列
[root@hadoop100 shell]# cat /etc/passwd | awk -F ":" '/^root/{print $7}'
/bin/bash

# 搜索 passwd 文件以 root 关键字开头的所有行,并输出该行的第 1 列和第 7 列,中间以逗号分割。
[root@hadoop100 shell]# cat /etc/passwd | awk -F ":" '/^root/{print $1","$7}'
root,/bin/bash

# 只显示/etc/passwd 的第一列和第七列,以逗号分割,且在所有行前面添加列名 user,shell 在最后一行添加"EOF"
# BEGIN 在所有数据读取行之前执行;END 在所有数据执行之后执行。
cat /etc/passwd | awk -F ":" 'BEGIN{print "user,shell"}//{print $1","$7}END{print "EOF"}'

# 将passwd 文件中的用户 id 增加数值 1 并输出
cat /etc/passwd | awk -F ":" '//{print $3+1}'

2.5 awk 的内置变量

2.6 案例实操

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 统计 passwd 文件名,每行的行号,每行的列
awk -F ":" '//{print "文件名称:"FILENAME, "行号:"NR, "列数:"NF}' /etc/passwd

# 查询 ifconfig 命令输出结果中的空
[root@hadoop100 pam.d]# ifconfig | awk -F "" '/^$/{print "空行:"NR}'
空行:9
空行:18
空行:26

# 切割IP地址
[root@hadoop100 pam.d]# ifconfig | awk -F " " '/netmask/{print "IP地址:"$2}'
IP地址:172.16.80.100
IP地址:127.0.0.1
IP地址:192.168.122.1