标准 I/O 和管道

1、标准输入和输出
1>程序:指令+数据(指令服务于数据)
  读入数据:input
  输出数据:output

2>三种 I/O 设备
  Linux 给程序提供三种 I/O 设备
    标准输入(STDIN) -0 默认接受来自键盘的输入
    标准输出(STDOUT)-1 默认输出到终端窗口
    标准错误(STDERR) -2 默认输出到终端窗口

3>把 I/O 重定向至文件
  I/O 重定向:改变默认位置
  标准输出的重定向:可以重定向至不同终端设备,也可以重定向至文件

[root@centos7 ~]#ls >output.txt    //>等同于1>

  标准错误的重定向:
    使用:2>
  >>两个大于号追加
  也可以将正确、错误分开重定向至不同的文件:

[root@centos7 ~]#ls /tmp/ /error >1.txt 2>2.txt

  正确错误混合重定向至一个文件:

[root@centos7 ~]#ls /tmp/ /error >f1 2>&1    //等同于ls /tmp/ /error %> f1

  cmd > log.txt 2>&1  //正确错误混合重定向
  cmd 2>&1 > log.txt  //错误显示,正确重定向
  cmd &> log.txt         //正确错误混合重定向
  cmd 2>log.txt >&2   //正确错误混合重定向

  >重定向即'覆盖';>>即追加

[root@centos7 ~]#ls
anaconda-ks.cfg  bin
[root@centos7 ~]#echo "123" > f1    //输出123重定向至f1(f1不存在则创建)
[root@centos7 ~]#cat f1
123
[root@centos7 ~]#set -C    //禁止覆盖
[root@centos7 ~]#echo "456" > f1
-bash: f1: 无法覆盖已存在的文件
[root@centos7 ~]#echo "456" >| f1    //强制覆盖
[root@centos7 ~]#cat f1
456
[root@centos7 ~]#set +C    //取消禁止覆盖

   可以将输出信息、垃圾文件重定向至垃圾桶:/dev/null

2、tr命令:转换和删除字符
  tr [OPTION]…SET1 [SET2]
    -c 取字符集的补集
    -d 删除所有属于第一字符集的字符
    -s 压缩字符
    -t 将第一个字符装换为第二个字符

[root@192 ~]#tr 'a-z' 'A-Z'    //将小写转换为大写
afgbsgsgfdfd    //支持标准输入
AFGBSGSGFDFD    //显示标准输出
[root@centos7 ~]#tr 'abc' '1234' //前少后多
abcdef
123def
[root@centos7 ~]#tr 'abcd' '123' //前多后少
abcdef
1233ef
[root@centos7 ~]#tr -t 'abcd' '123' //-t 前多后少
abcdef
123def
[root@centos7 ~]#tr -d abc //删除
abcdef
def

3、单行重定向

[root@centos7 ~]#cat >test1.txt
aaa    //输入aaa后在另一个终端查看,数据已经写入
bbb
^C
[root@centos7 ~]#

 4、多行重定向

[root@centos7 ~]#cat >test2.txt<<EOF
> aaa    //输入aaa,在另一个终端查看数据未写入
> bbb
> EOF    //输入终止词EOF数据写入
[root@centos7 ~]#

 5、管道
  管道(使用符号“|”表示)用来连接命令

[标准输出] 2>&1 | [标准输入]  //使用 2>&1 |,不论正确错误都输出(即|&)

  less:一页一页的查看输入

[root@centos7 ~]#ls -l /etc | less    //查看/etc下的目录文件,分页显示
......

  mail:通过邮件发送输入

echo “test email” | mail -s “test” [email protected]

  lpr:把输出发送到打印机

echo “test print” | lpr -P printer_name

  管道中-符号

打包再解压(例):tar -cvf - /home | tar -xvf -

 6、实例:运用管道、tr等命令实现1+2+...+100

[root@centos7 ~]#echo {1..100} | tr ' ' '+' | bc    //输出1-100,用+替换空格,经管道传递给bc计算器
5050
[root@centos7 ~]#seq -s + 1 100 | bc    //seq输出序列化的东西,输出1-100,-s指定分隔符
5050

猜你喜欢

转载自www.cnblogs.com/zyybky/p/12364781.html