管道符|在linux命令中非常实用,使用管道符就是将管道符前面的输出结果作为管道符后面的命令的输入,拿到结果后做什么命令就是你的事了。
比如:取出某文件内容的前三行信息
cat Fuck.txt
结果为:
public class Fuck {
public static void main(Strinig[] args) {
System.out.println("fuck...");
}
}
使用管道命令取出前三行:
cat Fuck.txt | head -3
结果为:
public class Fuck {
public static void main(Strinig[] args) {
System.out.println("fuck...");
使用管道符实现取出最常用的10条命令的实现方法:
(1) 第一步:获取所有执行过的命令,使用history
history
结果为(这里截取了一部分结果):
...
...
187 cat history.txt | awk '{print $2}' | sort | uniq -c
188 cat history.txt | awk '{print $2}' | sort | uniq -c | sort -n
189 cat history.txt | awk '{print $2}' | sort | uniq -c | sort -nr
190 cat history.txt | awk '{print $2}' | sort | uniq -c | sort -nr | head
191 ls -l | head -3
192 touch fuck.txt
193 touch hello.txt
194 touch world.txt
195 ls -l | head -3
196 ls -l
197 ls -l | head -3
198 ls -l | head 3
199 ls -l | head
200* ls -l | head 2
201 ls -l | head -2
202 ls -l | head -3
203 ls -al | head -3
204 ls -l | head -3
205 vim fuck.txt
206 mv fuck.txt Fuck.txt
207 ll
208 cat Fuck.txt
209 cat Fuck.txt | head -3
210 history
(2) 第二步:将获取到的命令结果重定向到一个文件中
history > history.txt
(3) 第三步:查看该文件的内容,得到命令信息
cat history.txt
(4) 第四步:从查看到的命令信息中过滤出来命令那一列
cat history.txt | awk '{print $2}'
结果为:
...
...
cat
cat
cat
cat
cat
ls
touch
touch
touch
ls
ls
ls
ls
ls
ls
ls
ls
ls
ls
vim
mv
ll
cat
cat
history
history
(5) 第五步:将得到的所有的命令,把相同命令放在一起
cat history.txt | awk '{print $2}' | sort
结果为:
...
...
service
service
service
shutdown
shutdown
shutdown
su
su
sync
tar
top
top
top
top
touch
touch
touch
useradd
useradd
useradd
useradd
userdel
usermod
var=123
var=123
(6) 第六步:将第五步得到的结果每个命令唯一显示并统计个数
cat history.txt | awk '{print $2}' | sort | uniq -c
结果为:
...
...
11 ping
7 ps
1 pstree
3 reboot
1 seq
5 service
3 shutdown
2 su
1 sync
1 tar
4 top
3 touch
4 useradd
1 userdel
1 usermod
2 var=123
1 var3=whoami
1 var3=`whoami`
1 var=whoami
1 var=`whoami`
10 vim
1 ./vmware-install.pl
1 whoami
1 whoani
(7) 第七步:将第六步的结果按照数量进行逆序排序
cat history.txt | awk '{print $2}' | sort | uniq -c | sort -nr
结果为:
20 ll
20 cat
18 cd
15 echo
12 ls
12 clear
11 ping
10 vim
9 ifconfig
8 chkconfig
7 ps
6 id
5 service
5 netstat
4 useradd
4 top
4 history
3 touch
3 shutdown
3 reboot
3 passwd
3 logout
3 groupadd
...
...
(8) 第八步:取出前10行
cat history.txt | awk '{print $2}' | sort | uniq -c | sort -nr | head
结果为:
20 ll
20 cat
18 cd
15 echo
12 ls
12 clear
11 ping
10 vim
9 ifconfig
8 chkconfig
总结:管道符|非常好用,用的也很多,需要掌握。
注意:
(1)head命令默认就是取前10行,可以人为指定,比如取前3行,head -3
(2)从命令信息中截取出命令那一列除了awk '{print $2}'外还有一种做法,cut -d ' ' -f5,意思就是按照空格分割,取第5列,有时候有多个空格在一起,不容易理解分割后命令那一列是第几列。因此推荐使用awk '{print $2}',这种写法就是默认按照空格分割。