我有辦法做到這一點嗎?例如,如果 a 得到一個長名稱,例如:
i-have-names-that-are-too-long-to-describe/
i-have-names-that-are-too-long-to-describe-2/
i-have-names-that-are-too-long-to-descri-3/
ls
如果ls -l
我的檔案或目錄名稱長度超過 20 個字符,我可以從 升級到 嗎?
有沒有辦法在 my 中設定 bash 函數.bashrc
來執行此操作?我將呼叫產生的函數 lls()。
@tripleee 問:
ls -l
當輸入檔名很長時你想要嗎?為什麼?它會使輸出更長,而不是更短。如果您收到長檔名和短檔名的混合怎麼辦?
我更想要它,以便閱讀長文件名被系統化到一個列表(並且更容易讓我消化和閱讀固定列);對於長檔名和短檔名的混合,我將預設使用清單格式。
答案1
沒有內建選項ls
可以滿足您的要求。您必須解析輸出,然後在找到“長”文件名時重新啟動,或執行以下操作:
$ ls ??????????* >& /dev/null && ls -l || ls
(輸入盡可能多的?
長度限制。您可以將其設定為別名。)
為什麼不直接使用呢ls -1
? (這是一個,而不是小寫的 L。)它總是在一列中列出文件。 (或透過管道連接ls
到more
或less
,這也可以連接到單列顯示。)或find
與 一起使用-maxdepth 1
。
答案2
if [ $(ls "$@" | ( max=0; while read l ; do len=${#l} ; [[ $max -lt $len ]] && max=$len; done; echo $max )) -gt 20 ]
then
ls "$@"
else
ls -l "$@"
fi
或者,感謝 manatwork 的建議,這種更簡單的方法假設 GNU wc 可用:
[[ $(ls "$@" | wc -L) -gt 20 ]] && ls "$@" || ls -l "$@"
答案3
這是我對自己想要的東西的獨立嘗試:
lls(){
opt=" "
for i in $(ls -l | tr -s " " | cut -d' ' -f9)
do
count=$(echo $i | wc -m)
if [ $count -gt 20 ] ; then
opt=" -l"; break;
fi
done
ls $opt
}
我把它放在我的 .bashrc 中。但這確實需要使用 tr、cut 和 wc。