输出重定向到原文件

  

因为没理解好输出重定向即管道的区别,哎..昨天踩了一个大坑。 废话少说,直接上命令: 

unexpand -a lcrs.cpp > lcrs.cpp             # 将文件file.txt内的所有空格转换为tabs(作用于expand相反)

结果是:   file.txt 内的内容被清空了(我去,我写了多久的代码T_T, 我以后不敢了)  

于是查了下bash的man手册

 Redirecting Output
       Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or  the
       standard  output (file descriptor 1) if n is not specified.  If the file does not exist it is created; if it does exist it is truncated to
       zero size.

       The general format for redirecting output is:

              [n]>word

       If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection  will  fail  if  the  file
       whose  name results from the expansion of word exists and is a regular file.  If the redirection operator is >|, or the redirection opera‐
       tor is > and the noclobber option to the set builtin command is not enabled, the redirection is attempted even if the file named  by  word
       exists.

简单说, 就是输出重定向的目标文件不存在的话,就创建空文件。 若文件存在,将文件清空!  因此:

unexpand -a lcrs.cpp > lcrs.cpp     #  > 右边目标文件lcrs.cpp存在,将其清空! unexpand对空文件进行操作,
                 # 再将结果输出到lcrs.cpp中!

                 # for me '>' 这符号具有误导性

How to resolve?      ans: 使用管道配合tee就行了或者使用vim  (还是vim好....)

unexpand -a file | tee file  > /dev/null

为了防止以后手贱, 将输出重定向到原操作文件! 将noclobber选项打开:

set -o noclobber      #  可使用 >| 来overrule 这个选项
原文地址:https://www.cnblogs.com/xsj24/p/4348310.html