菜鳥學Linux 第020篇筆記 find命令使用和命令組合條件

菜鳥學Linux 第020篇筆記  find命令使用和命令組合條件




grep, egrep, fgrep:文本查找


文件查找命令

locate

find


locate

非實時、模糊匹配 查找是根據全系統文件數據庫進行的;

updatedb 手動生成文件數據庫(注意有可能需要執行很長時間)

優點速度快

find

通過遍歷指定目錄中的所有文件完成查找

支持衆多查找標準

實時查找、精確、速度慢


命令格式

find 查找路徑 查找標準 查找到以後的處理動作



查找路徑:默認爲當前目錄

查找標準:默認爲指定路徑下的所有文件

處理動作:默認爲顯示


查找標準:

-name 'filename' 對文件做精確匹配

支持通配:

* 任意長度任意字符

? 匹配任意單個字符

[] 匹配括號內任意單個字符

-iname ‘Filename' 文件名匹配不區分大小寫

-regex PATTERN 基於正則表達式進行文件名匹配

-user username 根據文件的屬主來查找

-group groupname 

-uid User ID

-gid Group ID

-nouser 沒有屬主的文件

-nogroup 查找沒有屬組的文件

-type 查找文件類型

f ordinary file

d direcotry

c 字符設備

b block device

l 符號連接

p 管道設備

s 套接字設備

-size #爲數字

[+|-]#k 大於或小於#k

[+|-]#M

[+|-]#G

默認單位byte

-mtime 修改

-ctime 改變

-atime 訪問

[+|-]#

-mmin 分鐘

-cmin 分鐘

-amin 分鐘

[+|-]#

find /tmp -atime +30

-perm mode 以權限查找

find /tmp/ -perm 644 精確匹配

find /tmp/ -perm /644 只要有一位匹配就顯示 或關係

find /tmp/ -perm -644 只要包含就顯示 與關係

處理動作:默認爲print

-print 顯示

-ls 類似ls -l的形式顯示每一個文件的詳細

-ok command {} \; {}表示匹配到的 操作每次執行需要確認

-exec command {} \; 兩個都是將找到文件執行其它動作,即命令(不需要確認)

find -name "*.sh" -a -perm -111 -exec chmod o-x {} \;


小練習:

1、查找/var目錄下屬主爲root並且屬組爲mail的所有文件。

2、查找/usr目錄下不屬於root,bin,或student的文件;

3、查找/etc目錄下最近一週內內容修改過且不屬於root及student用戶的文件;

4、查找當前系統上沒有屬主或屬組且最近一天內曾被訪問過的文件,

   並將其屬主屬組改爲root;

5、查找/etc目錄下大於1M的文件,並將其文件名寫入/tmp/etc.largefiles文件中

6、查找/etc目錄下所有用戶都沒有寫權限的文件,顯示出其詳細信息;


德·摩根定律

非(P 且 Q) = (非 P) 或 (非 Q)

非(P 或 Q) = (非 P) 且 (非 Q)




Key

1. find /var -user root -a -group mail -a可加可不加


2. find /var -not -user root -o -not -user bin -o -not -user student

find /var -not \( -user root -a -not -user bin -a -not -user student )兩種解法


3. find /etc -mtime -7 -not -user root -a -not -user student

find /etc -mtime -7 -not \( -user root -o -user tom \)


4. find / \( -nouser -o -nogroup \) -a -atime -1 -exec chown root:root {} \;

5. find /etc -size +1 >> /tmp/etc.largefiles


6. find /etc -not -perm /222


寫命令錯誤總結:

1、用括號括起來的內容要加轉義字符\ 且括號後不可緊跟參數

2、參數前要記得加-

3、要牢記德摩根定律







組合條件查找

-a  與關係

-o 或關係

-not  非

e.g.   find /tmp -nouser -a type d -ls

find /tmp/ -nouser -o -type d -ls 

find /tmp -not -type d

find /tmp -not -type d -a -not -type s -ls

德·摩根定律

非(P 且 Q) = (非 P) 或 (非 Q)

非(P 或 Q) = (非 P) 且 (非 Q)





測試條件:

整數條件

-le

-lt

-ge

-gt

-eq

-ne

字符測試

==

!=

>

<

-n

-z

文件測試

-e

-f

-d

-r

-w

-x

組合測試條件

-a 與關係

-o 或關係

! 非關係

if [ $# -gt 1 -a $# -le 3]

[ $# -gt 8 -o $# -le 2]

[ $1 == 'Q' -o $1 == 'q' -o $1 == 'quit' -o $1 == 'Quit']

Script 1

求1-100所有偶數和奇數的和.

Key 1

#!/bin/bash

#

declare -i EVENSUM=0

declare -i ODDSUM=0


for I in {1..100}; do

 if [ $[$I%2] -eq 0 ]; then

EVENSUM+=$I

 else

ODDSUM+=$I

 fi

done

echo "odd=$ODDSUM even=$EVENSUM"


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章