我真的不知道我該怎么處理它。
對于 /etc 目錄中名稱以 o 或 l 開頭且第二個字母且名稱的第二個字母為 t 或 r 的每個檔案,顯示其名稱、大小和型別('file'/'directory'/'link ')。用途:通配符、for回圈和條件陳述句的型別。
#!/bin/bash
etc_dir=$(ls -a /etc/ | grep '^o|^l|^.t|^.r')
for file in $etc_dir
do
stat -c '%s-%n' "$file"
done
我正在考慮類似的事情,但我必須使用 if 陳述句。
uj5u.com熱心網友回復:
您可以使用find
命令達到目標。
這將搜索所有子目錄。
#!/bin/bash
_dir='/etc'
find "${_dir}" -name "[ol][tr]*" -exec stat -c '%s-%n' {} \; 2>/dev/null
要控制在子目錄中的搜索,您可以使用-maxdepth
標志,如下例所示,它將僅搜索/etc
dir 中的檔案和目錄名稱,而不通過子目錄。
#!/bin/bash
_dir='/etc'
find "${_dir}" -maxdepth 1 -name "[ol][tr]*" -exec stat -c '%s-%n' {} \; 2>/dev/null
您還可以使用-type f
OR-type d
引數相應地篩選僅查找檔案或目錄(如果需要)。
#!/bin/bash
_dir='/etc'
find "${_dir}" -name "[ol][tr]*" -type f -exec stat -c '%s-%n' {} \; 2>/dev/null
更新#1
由于您在評論中的要求,這是一條很長的路,但使用了for
回圈和if
陳述句。
注意:我強烈建議您查看并練習此腳本中使用的命令,而不是僅僅復制和粘貼它們以獲得分數;)
#!/bin/bash
# Set the main directory path.
_mainDir='/etc'
# This will find all files in the $_mainDir (ignoring errors if any) and assign the file's path to the $_files variable.
_files=$(find "${_mainDir}" 2>/dev/null)
# In this for loop we will
# loop over all files
# identify the poor filename from the whole file path
# and IF the poor file name matches the statement then run & output the `stat` command on that file.
for _file in ${_files} ;do
_fileName=$(basename ${_file})
if [[ "${_fileName}" =~ ^[ol][tr].* ]] ;then
stat -c 'Size: %s , Type: %n ' "${_file}"
fi
done
exit 0
uj5u.com熱心網友回復:
您應該將問題分解為多個部分并一一解決。
首先,嘗試構建一個能找到正確檔案的運算式。如果您要在 shell 中執行正則運算式:
ls -a /etc/ | grep '^o|^l|^.t|^.r'
您會立即看到您沒有得到正確的輸出。因此,第一步是了解 grep 的作業原理并將運算式修復為:
ls -a /etc/ | grep '^[ol][tr]*'
然后,您有了檔案名,并且需要大小和文本檔案型別。stat
使用呼叫很容易獲得大小。
但是,您很快就會意識到您不能通過-f
開關要求 stat 提供檔案型別的文本格式,因此您可能必須使用 if 子句來呈現它。
uj5u.com熱心網友回復:
這個怎么樣:
shopt extglob
ls -dp /etc/@(o|l)@(t|r)* | grep -v '/$'
解釋
shopt extglob
- 啟用擴展通配符(https://www.google.com/search?q=bash extglob)ls -d
- 列出目錄名稱,而不是它們的內容ls -dp
- 并/
在每個目錄名稱的末尾添加@(o|l)@(t|r)
-o
或l
一次 (@
),然后t
或r
一次grep -v '/$'
- 洗掉所有包含/
在末尾的行
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/532900.html
上一篇:為什么對于定義了索引值為0的陣列,我會收到“無法讀取未定義的屬性'0'”?
下一篇:Python中的“繼續”功能