清空文件方法总结

清空文件方法总结

清空文件的原理一般都是将空的内容重定向至文件,来达到这种目的。

  1. 通过 true 关键字

    [root@localhost tmp]# cat test.txt
    hello shell
    [root@localhost tmp]#
    [root@localhost tmp]# true > test.txt
    [root@localhost tmp]#
    [root@localhost tmp]# cat test.txt
    [root@localhost tmp]#
    
    
  2. 通过 > 符号

      [root@localhost tmp]# cat test.txt
      hello world
      [root@localhost tmp]#
      [root@localhost tmp]# > test.txt
      [root@localhost tmp]#
      [root@localhost tmp]# cat test.txt
      [root@localhost tmp]#
    
  3. 通过 /dev/null 特殊文件

    [root@localhost tmp]# cat test.txt
    hello billy
    [root@localhost tmp]#
    [root@localhost tmp]# `cat /dev/null` > test.txt
    [root@localhost tmp]#
    [root@localhost tmp]# cat test.txt
    [root@localhost tmp]#
    
    
  4. 通过 echo 命令

    [root@localhost tmp]# cat test.txt
    hello boy
    [root@localhost tmp]#
    [root@localhost tmp]# echo ' ' > test.txt
    [root@localhost tmp]#
    [root@localhost tmp]# cat test.txt
    
    [root@localhost tmp]#
    

    Note:会产生一行空行,能达到目的,也存在这个弊端

  5. 通过 truncate 命令

    [root@localhost tmp]# cat test.txt
    hello java
    [root@localhost tmp]#
    [root@localhost tmp]# truncate -s 0 test.txt
    [root@localhost tmp]#
    [root@localhost tmp]# cat test.txt
    [root@localhost tmp]#
    
posted @ 2021-12-28 19:36  流~~苏  阅读(377)  评论(0)    收藏  举报