linux清空文件文本内容

linux清空文件文本内容,第1张

  以前一直用echo的方式来清空一个文件内容,例如 echo “” >file_name,这样虽说能清掉文件的内容,但是文件会有一个空行,其实cat能更好的胜任此项任务,cat 一个空文件然后重定向文件即可。那里去找这个空文件呢,系统的/dev/null就是一个很好选择,所以如下命令

就可以彻底清空文件的内容了。

1、使用重定向的方法

[root@centos7 ~]# du -h test.txt

4.0Ktest.txt

[root@centos7 ~]# >test.txt

2、使用true命令重定向清空文件

[root@centos7 ~]# du -h test.txt

4.0Ktest.txt

[root@centos7 ~]# true >test.txt

[root@centos7 ~]# du -h test.txt

0test.txt

3、使用cat/cp/dd命令及/dev/null设备来清空文件

[root@centos7 ~]# du -h test.txt

4.0Ktest.txt

[root@centos7 ~]# cat /dev/null > test.txt

[root@centos7 ~]# echo "Hello World" >test.txt

[root@centos7 ~]# du -h test.txt

4.0Ktest.txt

[root@centos7 ~]# cp /dev/null test.txt

cp:是否覆盖"test.txt"? y

[root@centos7 ~]# echo "Hello World" >test.txt

[root@centos7 ~]# dd if=/dev/null of=test.txt

4、使用echo命令清空文件

[root@centos7 ~]# echo "Hello World" >test.

[root@centos7 ~]# echo -n "" >test.txt==>要加上"-n"参数,默认情况下会"\n",也就是回车符

5、使用truncate命令清空文件

[root@centos7 ~]# du -h test.txt

4.0Ktest.txt

[root@centos7 ~]# truncate -s 0 test.txt -s参数用来设定文件的大小,清空文件,就设定为0;


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8680041.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-19
下一篇 2023-04-19

发表评论

登录后才能评论

评论列表(0条)

保存