Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> 學習 Linux

Linux 檔案操作常用指令大整理

Linux 檔案操作常用指令大整理

日常維運時,總有一些關於檔案的查詢與統計需求會反覆出現。我把這些指令整理成一份對照表,方便隨手查閱,後續也會持續補充。

目錄樹與容量

列出目前目錄的樹狀結構:

[root@DB-Server ~]# tree

列出指定目錄的樹狀結構:

[root@DB-Server ~]# tree /home/oracle/kerry

查看某目錄的總大小:

[root@DB-Server ~]# du -sh /u01
[root@DB-Server ~]# du -sh

逐一列出底下每個檔案與子目錄的大小:

[root@DB-Server ~]# du -sh *

搜尋與計數

搜尋檔案並列印結果:

[root@DB-Server ~]# find /home/oracle -name "awr*" -print

統計目前目錄下的檔案與目錄總數:

[root@DB-Server ~]# ls -lrt | grep -v 'total' | wc -l

只算檔案數(不含子目錄):

[root@DB-Server ~]# ls -l | grep "^-" | wc -l

算檔案數(含子目錄內的):

[root@DB-Server ~]# ls -l * | grep "^-" | wc -l

只看子目錄數量:

[root@DB-Server ~]# ls -l | grep "^d" | wc -l

只列出子目錄名稱(注意這個寫法不會深入子目錄的子目錄):

[root@DB-Server ~]# ls -F | grep /$

內容擷取

取出檔案的某一欄:

[root@DB-Server ~]# cat /etc/passwd | awk -F ":" '{print $1}'

看前 N 行:

[root@DB-Server ~]# head -5 /etc/passwd

看後 N 行:

[root@DB-Server ~]# tail -5 /etc/passwd

看第 5 到 10 行:

[root@DB-Server ~]# sed -n '5,10p' /etc/passwd

三個時間戳的真相

Linux 其實沒有「建立時間」這個欄位,只有 Access(存取)、Modify(內容修改)、Change(狀態變更)三個。用 stat 可以一次看齊:

[root@DB-Server ~]# touch test
[root@DB-Server ~]# stat test
  File: `test'
  Size: 0             Blocks: 0          IO Block: 4096   regular empty file
Device: 802h/2050d    Inode: 4196044     Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/   root)   Gid: (    0/   root)
Access: 2016-07-25 15:53:07.000000000 +0800
Modify: 2016-07-25 15:53:07.000000000 +0800
Change: 2016-07-25 15:53:07.000000000 +0800

只要檔案從建立後沒被改過,就可以把 Modify 當成建立時間;同理,狀態沒變過就等於 Change,沒被讀過就等於 Access。實務上幾乎不可能三者都相同,因為檔案一被讀取 Access 就變了:

[root@DB-Server ~]# cat test
[root@DB-Server ~]# stat test
Access: 2016-07-25 16:20:20.000000000 +0800
Modify: 2016-07-25 15:53:07.000000000 +0800
Change: 2016-07-25 15:53:07.000000000 +0800

反過來,用 vi 寫入內容後,Modify 與 Change 會一起更新,Inode 也可能因為重寫而改變:

[root@DB-Server ~]# stat test
  Size: 10            Blocks: 8          IO Block: 4096   regular file
Inode: 4196050
Access: 2016-07-25 16:21:31.000000000 +0800
Modify: 2016-07-25 16:21:31.000000000 +0800
Change: 2016-07-25 16:21:31.000000000 +0800

依時間批次刪除

分別刪除狀態變更超過 5 天、內容修改超過 5 天、存取超過 5 天的檔案(前兩種最常用):

find . -type f -ctime +5 -delete
find . -type f -mtime +5 -delete
find . -type f -atime +5 -delete

上面只會刪檔案,不會動目錄。要連目錄一起清掉,改用:

find /backup/mysql -mtime +5 -name "*.*" -exec rm -rf {} \;

提醒一句:-delete 與 -exec rm -rf 都不會再問你一次,正式環境上跑之前,先把 -delete 換成 -print 確認名單,會安全很多。

Copyright © Linux教程網 All Rights Reserved