Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Shell 程式設計

用 Shell 為各子目錄生成不含自身的檔案列表

需求:/home/file1/free 底下有部分子目錄含有 list.php,而 list.php 本身就是該目錄的檔案列表,因此生成內容時必須把它自己排除掉。

SHELL 實作:

cd /home/file1/free
find . -name "list.php" > /home/nexian/free.txt
sed -i 's/list.php//g' /home/nexian/free.txt
sed -i 's/\.\///g' /home/nexian/free.txt
lsnum=`cat /home/nexian/free.txt`
for x in $lsnum
do
cd /home/file1/free/$x
echo $x
mv list.php list2.php
ls -p | grep "[^/]$" > list.php
sed -i "/list.php/d" list.php
sed -i "/list2.php/d" list.php
done

流程是:先用 find 找出所有 list.php 路徑,用 sed 把檔名與 ./ 前綴去掉,得到純目錄清單;接著逐目錄把舊的 list.php 改名為 list2.php,重新產生列表,再把兩個自身檔名從列表中刪掉,避免自我引用。

ls 的過濾技巧

只列出檔案、不列出目錄:

ls -l | grep ^-
ls -p | grep "[^/]$"

只列出目錄、不列出檔案:

ls -l | grep '^d'
ls -lF | grep /

原理是 -p 或 -F 會在目錄名後加上 / 作為標記,再用 grep 反向匹配就能把兩類分開。

實作建議:cd 放在迴圈裡容易在出錯時把後續路徑搞亂,改成 ls -p | grep "[^/]$" > "/home/file1/free/$x/list.php" 用絕對路徑會安全得多。

Copyright © Linux教程網 All Rights Reserved