[教程] Linux文件清空的五种方法总结分享

[复制链接]
发表于 2023-11-25 00:00:00 | 显示全部楼层 |阅读模式

本文主要介绍的是Linux文件清空的五种方法,下面话不多说,来看看详细的介绍吧。

1、使用重定向的方法

?
1
2
3
4
5
[root@centos7 ~]# du -h test.txt
4.0K test.txt
[root@centos7 ~]# > test.txt
[root@centos7 ~]# du -h test.txt
0 test.txt

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

?
1
2
3
4
5
[root@centos7 ~]# du -h test.txt
4.0K test.txt
[root@centos7 ~]# true > test.txt
[root@centos7 ~]# du -h test.txt
0 test.txt

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[root@centos7 ~]# du -h test.txt
4.0K test.txt
[root@centos7 ~]# cat /dev/null > test.txt
[root@centos7 ~]# du -h test.txt
 test.txt
###################################################
[root@centos7 ~]# echo "Hello World" > test.txt
[root@centos7 ~]# du -h test.txt
4.0K test.txt
[root@centos7 ~]# cp /dev/null test.txt
cp:是否覆盖"test.txt"? y
[root@centos7 ~]# du -h test.txt
 test.txt
##################################################
[root@centos7 ~]# echo "Hello World" > test.txt
[root@centos7 ~]# du -h test.txt
4.0K test.txt
[root@centos7 ~]# dd if=/dev/null of=test.txt
记录了0+0 的读入
记录了0+0 的写出
0字节(0 B)已复制,0.000266781 秒,0.0 kB/秒
[root@centos7 ~]# du -h test.txt
 test.txt

4、使用echo命令清空文件

?
1
2
3
4
5
6
[root@centos7 ~]# echo "Hello World" > test.txt
[root@centos7 ~]# du -h test.txt
4.0K test.txt
[root@centos7 ~]# echo -n "" > test.txt ==>要加上"-n"参数,默认情况下会"\n",也就是回车符
[root@centos7 ~]# du -h test.txt
0 test.txt

5、使用truncate命令清空文件

?
1
2
3
4
5
[root@centos7 ~]# du -h test.txt
4.0K test.txt
[root@centos7 ~]# truncate -s 0 test.txt -s参数用来设定文件的大小,清空文件,就设定为0;
[root@centos7 ~]# du -h test.txt
0 test.txt

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。

原文链接:http://www.cnblogs.com/mrwang1101/p/6166326.html

回复

使用道具 举报

发表于 2026-10-11 00:58:56 | 显示全部楼层
哇,整理得很详细啊!刚好最近在清理日志文件,正需要这些技巧。

补充一下个人心得:

1. 对于正在被程序写入的日志文件,直接清空可能会导致问题,最好先重命名再创建新文件,或者使用`logrotate`工具来管理。

2. `truncate`命令很适合处理大文件,速度比`cp /dev/null`快很多,特别是对于GB级别的文件。

3. 如果要清空目录下的所有文件,可以用`find . -type f -exec truncate -s 0 {} \;`这样的命令批量处理。

4. 还有一种方法是使用`: > filename`,冒号是bash内置命令,效果和`> filename`一样,而且更简洁。

感谢分享,收藏了!以后再遇到需要清空文件的情况就不用再百度了。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

圆梦公社,专注于为全球华人提供纯粹技术交流的地方,请勿发布任何政治及违法的言论。如有相关侵权、举报、投诉及建议等,请发 E-mail:dzh188@hotmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部