前言
这以部分让我们来了解,Linux中的文件,以及IO重定向吧~
VX: wenjinworkon
目录
IO重定向
1.1 标准输入和输出
输入数据:Input
输出数据:Output
打开文件都有一个fd: file descriptor(文件描述符)
Linux提供了三种I/O设备:
- 标准输入(STDIN) -0 默认接受来自终端窗口的输入
- 标准输出(STDOUT) -1 默认输出到终端窗口
- 标准错误(STDERR) -2 默认输出错误到终端窗口
[root@centos8 ~]#cat test.txt
hello
[root@centos8 ~]#cat file.py
import time
f = open('test.txt','r')
time.sleep(1000)
[root@centos8 ~]#python3 file.py
[root@centos8 ~]#ll /proc/`pidof python3`/fd
total 0
lrwx------ 1 root root 64 Apr 6 18:13 0 -> /dev/pts/0
lrwx------ 1 root root 64 Apr 6 18:13 1 -> /dev/pts/0
lrwx------ 1 root root 64 Apr 6 18:13 2 -> /dev/pts/0
lr-x------ 1 root root 64 Apr 6 18:13 3 -> /root/test.txt
1.2 I/O重定向
I/O重定向:将标准输出、标准输入、标准错误指向新的目标
支持的操作符:
格式:
命令 操作符号 文件名
&> 将标准输出和错误都重定向
1> 或 > 把STDOUT重定向到文件
2> 把STDERR重定向到文件
#以上如果文件已经存在,文件内容可能会被覆盖
追加
>> 追加标准输出重定向到文件
2>> 追加标准错误重定向到文件
eg.1 标准输出和错误输出到各自不同位置
COMMAND > /path/to/file.out 2> /path/to/error.out
1.3 标准输入重定向
从文件中导入STDIN,替代当前终端的输入设备,使用<来重定向标准输入
某些命令能够接受从文件中导入的STDIN
1.3.1 tr 命令
tr 转换和删除字符
tr [option] ... SET1 [SET2]
选项
-d --delete:删除所有属于第一字符集的字符
-s --squeeze-repeats:把连续重复的字符以单独一个字符表示,即去重
-t --truncate-set1:将第一个字符集对应字符转化为第二字符集对应的字符
-c –C --complement:取字符集的补集
eg.1 将文件中的小写转换成大写字母
tr 'a-z' 'A-Z' < /root/test
1.3.2 标准输入重定向
实现标准输入重定向的符号
command < file
eg.1
cat > /root/file1
123
hello world
123
^C
#crtl+d 退出
多行重定向
通过 "<<" 来实现标准输入的终止,其中EOF为最常用的终止词
cat > /root/file2 <<EOF
123
hello world
123
EOF
管道
2.1 管道
管道 "|" 用来连接多个命令

格式:
command1 | command2 | command3
功能说明:
将命令1的STDOUT发送给命令2的STDIN,命令2的STDOUT发送到命令3的STDIN
所有命令会在当前shell进程的子shell进程中执行
eg.1
[root@centos8 ~]# ll /etc/ | grep shadow
---------- 1 root root 432 May 5 16:18 gshadow
----------. 1 root root 422 May 5 16:17 gshadow-
---------- 1 root root 745 May 5 16:18 shadow
----------. 1 root root 724 May 5 16:17 shadow-
2.2 tee 命令
该命令主要用于重定向到多个目标
command1 | tee [-a ] filename | command2
-a:表示追加
eg.1 通过 tee 命令将命令1的操作重定向到 test 文件
[root@centos8 ~]# ll /etc/ | tee -a test | grep shadow
---------- 1 root root 432 May 5 16:18 gshadow
----------. 1 root root 422 May 5 16:17 gshadow-
---------- 1 root root 745 May 5 16:18 shadow
----------. 1 root root 724 May 5 16:17 shadow-
#将会把command1 的执行结果输出到test文件
[root@centos8 ~]# ls
test
总结
以上就是IO重定向以及管道的理解和使用操作了,欢迎添加VX交流:wenjinworkon
1万+

被折叠的 条评论
为什么被折叠?



