1. 程式人生 > >Linux文件清空的幾種方法

Linux文件清空的幾種方法

dd命令 txt cat 重定向 是否 hello 情況 命令 world

1、使用重定向的方法

[[email protected] ~]# du -h test.txt 
4.0K    test.txt
[[email protected] ~]# > test.txt 
[[email protected] ~]# du -h test.txt 
0    test.txt

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

[[email protected] ~]# du -h test.txt 
4.0K    test.txt
[[email protected] ~]# true > test.txt 
[[email protected] ~]# du -h test.txt 
0    test.txt

3、使用cat/cp/dd命令及/dev/null設備來清空文件

[[email protected] ~]# du -h test.txt 
4.0K    test.txt
[[email protected] ~]# cat /dev/null >  test.txt 
[[email protected] ~]# du -h test.txt 
0    test.txt
################################################### [[email protected] ~]# echo "Hello World" > test.txt [[email protected] ~]# du -h test.txt 4.0K test.txt [[email protected] ~]# cp /dev/null test.txt cp:是否覆蓋"test.txt"? y [[email protected] ~]# du -h test.txt 0 test.txt
################################################## [[email protected] ~]# echo "Hello World" > test.txt [[email protected] ~]# du -h test.txt 4.0K test.txt [[email protected] ~]# dd if=/dev/null of=test.txt 記錄了0+0 的讀入 記錄了0+0 的寫出 0字節(0 B)已復制,0.00041594 秒,0.0 kB/秒 [[email protected] ~]# du -h test.txt 0 test.txt

4、使用echo命令清空文件

[[email protected] ~]# echo "Hello World" > test.txt 
[[email protected] ~]# du -h test.txt 
4.0K    test.txt
[[email protected] ~]# echo -n "" > test.txt    #要加上"-n"參數,默認情況下是"\n",就是回車符
[[email protected] ~]# du -h test.txt  
0    test.txt

5、使用truncate命令清空文件

[[email protected] ~]# du -h test.txt 
4.0K    test.txt
[[email protected] ~]# truncate -s 0 test.txt   -s參數用來設定文件的大小,清空文件,就設定為0;
[[email protected] ~]# du -h test.txt 
0    test.txt

Linux文件清空的幾種方法