Shell入门(六)之Shell pipe(管道)
Shell pipe(管道)命令
pipe(管道)命令使用|
界定符号。
pipe管道命令|
,仅能处理经由前面一个指令传来的信息,也就是标准输出(standard output)的信息,对于标准错误输出(standard error output)没有处理能力。整体的pipe管道命令可以使用下图表示:
eg:在当前用户执行ls -al | more
,可以看到是以more形式显示,如下图:
除此之外,pipe还有一些其他的命令。
撷取命令:cut、grep
cut
选项与参数
-d
:后面接分隔字符。与-f
一起使用。-f
:依据-d
的分隔字符将一段信息分隔数段,用-f
取出第几段的意思。-c
:以字符的单位取出固定字符区间
eg:
[zhang@localhost ~]$ echo "hello world" | cut -d "o" -f 1
hell
[zhang@localhost ~]$ echo "hello world" | cut -d "o" -f 2
w
[zhang@localhost ~]$ echo "hello world" | cut -d "o" -f 3
rld
[zhang@localhost ~]$ echo "hello world" | cut -c 3
l
[zhang@localhost ~]$ echo "hello world" | cut -c 5
o
[zhang@localhost ~]$ echo "hello world" | cut -c 9
r
grep
grep选项与参数:
-a
:将binary档案以text档案的方式搜寻数据-c
:计算找到’搜寻字符串’的次数-i
:忽略大小写-n
:顺便输出行号-v
:反向选择,亦即显示出没有’搜寻字符串’内容的那一行--color=auto
:可以将找到的关键字部分加上颜色显示。color有三种参数(auto,always,never)
eg:
现在1.txt输入一些数据,如:
[zhang@localhost ~]$ cat 1.txt
hello world
abcdefg hijklmn
opqrst uvwxyz
abc
hello
world
HEllo1
hello2
world3
[zhang@localhost ~]$ cat 1.txt | grep hello
hello world
hello
hello2
搜索到的hello字段,默认红色,如果加上--color=never
可以去掉颜色。
添加-n
参数,可以输出行号。
[zhang@localhost ~]$ cat 1.txt | grep hello -n
1:hello world
5:hello
21:hello2
添加-i
参数,忽略大小写。
[zhang@localhost ~]$ cat 1.txt | grep hello -i
hello world
hello
HEllo1
hello2
|
连续使用
[zhang@localhost ~]$ cat 1.txt | grep o | grep w
hello world
opqrst uvwxyz
world
world3
排序命令:sort、wc、uniq
sort
选项与参数
-f
:忽略大小写的差异-b
:忽略最前面的空格部分-M
:以月份的名字来排序-n
:使用纯数字进行排序-r
:反向排序-u
:就是uniq,相同的数据中,仅出现一行代表-t
:分隔符,预设是用tab键来分隔-k
:以那个区间filed来进行排序
eg:
sort进行排序:
[zhang@localhost ~]$ cat 1.txt | sort
abc
abcdefg hijklmn
hello
HEllo1
hello2
hello world
opqrst uvwxyz
world
world3
-r
参数进行反向排序
[zhang@localhost ~]$ cat 1.txt | sort -r
world3
world
opqrst uvwxyz
hello world
hello2
HEllo1
hello
abcdefg hijklmn
abc
wc
如果我们想知道
1.txt
中有多少行,多少个单词,多少个字符。我们可以使用wc
命令。选项与参数
-l
:今列出行-w
:今列出多少字(英文单词)-m
:多少字符
eg:
[zhang@localhost ~]$ wc 1.txt
9 12 79 1.txt
[zhang@localhost ~]$ wc 1.txt -l
9 1.txt
[zhang@localhost ~]$ wc 1.txt -w
12 1.txt
[zhang@localhost ~]$ wc 1.txt -m
79 1.txt
uniq
选项与参数
-i
:忽略大小写-c
:进行计数
[zhang@localhost ~]$ cat 2.txt
hello
Hello
WOrld
abc
abc
ABC
hello1
对2.txt
进行sort后,进行uniq。
[zhang@localhost ~]$ cat 2.txt | sort | uniq
abc
ABC
hello
Hello
hello1
WOrld
进行sort,使用uniq忽略大小写
[zhang@localhost ~]$ cat 2.txt | sort | uniq -i
abc
hello
hello1
WOrld
进行sort,使用uniq进行计数
[zhang@localhost ~]$ cat 2.txt | sort | uniq -c
2 abc
1 ABC
1 hello
1 Hello
1 hello1
1 WOrld