linux学习笔记9-输出输入重定向
linux学习笔记9-输出输入重定向
unix ken tompsan 准则:一次只做一件事,并且做好。但是这只适用于目标明确且单一的情况。
后面又有了另一个准则,doug mcllroyme美国工程院院士,计算机大师,扩展到,能够与其他程序协同工作,并且能处理文本流。
让linux程序之间协同工作需要用到:
Redirection 重定向(输入输出重定向)和 pipe管道
stdin 标准输入 0
stdout 标准输出 1
stderr 标准错误输出 2
输出重定向
linux使用 > 和 >>来重定向标准输入
ls -l ./example/ >result.txt
把example目录的文件列表输出到result.txt文件中
如果result.txt文件不存在,会被创建。如果已经存在,则会被覆盖。
如果把 > 改为 >>,则新的输出结果会追加到之前存放结果的文件中,并不会覆盖。
接上个命令
ls -l ./ >>result.txt
把当前目录的文件列表追加输出到刚才的result.txt文件中
还可以分别把正确和错误的输出结果做2个分开的保存
例如当前目录只有 file01-file03 文件
ll ./file01 ./file02 ./file03 ./file04 1>./stdout.txt 2>./stderr.txt
[stu@localhost example]$ cat stderr.txt
ls: 无法访问file04: 没有那个文件或目录
[stu@localhost example]$ cat stdout.txt
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file01
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file02
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file03
还可以把正确和错误的输出存到同一个文件里面
例如当前目录只有 file01-file03 文件
[stu@localhost example]$ ll file04 file01 file02 file03 &>result.txt
[stu@localhost example]$ cat result.txt
ls: 无法访问file04: 没有那个文件或目录
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file01
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file02
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file03
结合回显命令echo把回显内容直接输出到文件里面其中 -e选项是输出转义字符,其中 \n 代表回车;-n参数代表显示行号
[stu@localhost example]$ echo -e "1 apple\n2 pear\n3 banana"
1 apple
2 pear
3 banana
[stu@localhost example]$ echo -e "1 apple\n2 pear\n3 banana">fruit.txt
[stu@localhost example]$ cat -n fruit.txt
1 1 apple
2 2 pear
3 3 banana
使用重定向来忽略错误的输出,把错误的输出丢弃到“系统黑洞”
例如当前目录只有 file01-file03 文件
[stu@localhost example]$ ll file01 file02 file03 file04 2>/dev/null
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file01
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file02
-rw-rw-r--. 1 stu stu 0 1月 6 20:48 file03
其中/dev/null文件是 系统黑洞,被输出到这个文件的内容都被丢弃,查看命令看不到里面有任何内容
输入重定向
让系统从指定的文件中获得输入,而不是从键盘中
< 和<<
[stu@localhost example]$ cat fruit.txt
1 apple 2 pear 3 banana
[stu@localhost example]$ tr '\t' '\n'
tr命令表示从标准输入中替换特定字符并把结果给到标准输出。
tr【将被替换掉的字符】【新的字符】
此例中表示把\t 换为\n以后再输出结果。
sort -k【关键字字段序号】【要排序的文本文件】
一种特殊的输入重定向叫 Here Document,将输入重定向到一个交互式 Shell 脚本或程序。下面例子中的<<【特定词】,sort -k2表示对文本文件中第2列的值根据ASC码进行重排。
[stu@localhost ~]$ sort -k2 < EOF(要顶格写,前面不能有任何字符或空格)
F 1
D 2
V 4
D 6
[stu@localhost ~]$ sort -k2 < a 9
> a 8
> a 7
> a 1
> a 3
> a 6
> ok
a 1
a 3
a 6
a 7
a 8
a 9
其中EOF表示 End Of File,在操作系统中表示资料源无更多的资料可读取。资料源通常称为档案或串流。通常在文本的最后存在此字符表示资料结束。