目录
4、注意 printf 需要加换行符 print 直接默认换行
一、cut 命令
1、准备一个文件 如下
2、提取第二列
[root@hadoop ~]# cut -f 2 student.txt
Name
aa
bb
cc
dd
3、提取多列
[root@hadoop ~]# cut -f 2,4 student.txt
Name Mark
aa 88
bb 50
cc 78
dd 90
4、指定分隔符提取
例如 提取 /etc/passwd 文件 是以 : 分隔的
可以使用
[root@hadoop ~]# cut -d ':' -f 1 /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
-d 后面指定分隔符 然后 -f 指定要提取的列
[root@hadoop ~]# cat /etc/passwd | grep /bin/bash |grep mysql|cut -d ':' -f 1
mysql
通过管道 提取自己想要的东西
grep -v 是反向提取
!!!! cut命令无法以空格作为分隔符
二 、awk
1、基本格式
awk '条件1{动作1}条件2{动作2}.....' 文件名
2、一个例子,输出一个文件第二列与第四列
[root@hadoop ~]# cat student.txt
ID Name Gender Mark
1 aa M 88
2 bb M 50
3 cc M 78
4 dd M 90
[root@hadoop ~]# awk '{printf $2 "\t" $4 "\n"}' student.txt
Name Mark
aa 88
bb 50
cc 78
dd 90
3、第二个例子 df -h
[root@hadoop ~]# df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 3.9G 0 3.9G 0% /dev
tmpfs 3.9G 24K 3.9G 1% /dev/shm
tmpfs 3.9G 824K 3.9G 1% /run
tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup
/dev/vda1 99G 19G 76G 20% /
tmpfs 783M 0 783M 0% /run/user/0
tmpfs 783M 0 783M 0% /run/user/1001
[root@hadoop ~]# df -h | grep vda | awk '{printf $1 "\t" $5 "\n"}'
/dev/vda1 20%
4、注意 printf 需要加换行符 print 直接默认换行
5、第二个例子 df -h 升级版
[root@hadoop ~]# df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 3.9G 0 3.9G 0% /dev
tmpfs 3.9G 24K 3.9G 1% /dev/shm
tmpfs 3.9G 824K 3.9G 1% /run
tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup
/dev/vda1 99G 19G 76G 20% /
tmpfs 783M 0 783M 0% /run/user/0
tmpfs 783M 0 783M 0% /run/user/1001
[root@hadoop ~]# df -h | grep vda | awk '{print $5}'|cut -d '%' -f 1
20
6、BEGIN
(1)begin 会在真正的动作执行前先做一个动作
[root@hadoop ~]# awk 'BEGIN {print "test11111"}{print $2 "\t" $4}' student.txt
test11111
Name Mark
aa 88
bb 50
cc 78
dd 90
(2)和分隔符一起使用
不加BEGIN
[root@hadoop ~]# awk '{FS = ":"}{print $1}' /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
nobody
systemd-network
dbus
polkitd
libstoragemgmt
rpc
因为 awk 是先读取一行数据 ,然后后面再做处理 ,所以我们可以强制加一个BEGIN
[root@hadoop ~]# awk 'BEGIN{FS = ":"}{print $1}' /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
nobody
systemd-network
dbus
polkitd
libstoragemgmt
rpc
ntp
7 、END
(1)最后执行动作
[root@hadoop ~]# awk 'BEGIN{FS = ":"}END{print "aaaaaaa"}{print $1}' /etc/passwd
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
nobody
systemd-network
dbus
polkitd
libstoragemgmt
rpc
ntp
abrt
sshd
postfix
chrony
tcpdump
syslog
lighthouse
peizk
openvpn
mysql
aaaaaaa
8、条件可以是 判断
[root@hadoop ~]# cat student.txt
ID Name Gender Mark
1 aa M 88
2 bb M 50
3 cc M 78
4 dd M 90
[root@hadoop ~]# cat student.txt | grep -v Name | awk '$4 >89 {print $2}'
dd