給定一個根路徑,我試圖遍歷子目錄以遍歷每個子目錄中的檔案并列印檔案的名稱。
目錄結構是這樣的:
- 根目錄
目錄2,
- 檔案{1..10}
目錄3,
- 檔案{1..10}
目錄4
- 檔案{1..10}
我想遍歷 dir2 并列印其中的所有檔案名。然后遍歷 dir3 并列印所有檔案名......等等
這是我到目前為止所擁有的:
#!/bin/bash
#!/bin/sh
cd /the/root/directory
for dir in */
do
for FILE in dir
do
echo "$FILE"
done > /the/root/directory/filenames.txt
done
這是我在 filenames.txt 中得到的輸出:
dir
我的預期輸出應該是:
file{1..10}
file{1..10}
file{1..10}
我是 bash 腳本的初學者......一般來說腳本很好。任何幫助是極大的贊賞!
uj5u.com熱心網友回復:
你沒有提到你的最終目標是什么,所以我在這里推測一下。
如果您的最終目標是僅在串列中遞回地查看檔案,則只需運行一個簡單的 find 命令:
find . -type f
或者,如果您想查看詳細資訊:
find . -type f -ls
使用顏色和漂亮的 ansi 條查看它們的好方法是安裝tree命令。示例:
https ://www.tecmint.com/linux-tree-command-examples/
如果您的需求很簡單,例如,您想對每個檔案執行諸如 a 之類的操作tail -n1,則可以將命令通過管道傳遞給xargs這樣的:
find . -type f | xargs tail -n1
但是,如果您的最終目標是使用 bash 以某種方式處理它們,那么您可以繼續使用 bash 回圈方法,如@tjm3772.
你提到你只是在尋找檔案名,所以你可以運行:
find . -type f | sed 's/.*\///'
如果要將其寫入檔案,只需將輸出重定向到您選擇的檔案名:
find . -type f | sed 's/.*\///' > filename.txt
uj5u.com熱心網友回復:
您可以使用 find 命令,這將遍歷目錄而不需要 for 回圈
my_bash_script.sh:
find * -type d > filenames.txt
將此腳本放在目錄的同一級別,或者通過更改*路徑將其指向該位置
注意:如果在終端中顯示權限被拒絕,請運行:chmod u x the_script_name.sh
uj5u.com熱心網友回復:
您忘記$dir在內部回圈中展開,因此回圈執行一次,將 FILE 設定為文字字串 'dir' 而不是目錄名稱。
之后,您需要一個通配模式來擴展目錄中的檔案名。
固定示例:
#!/bin/bash
cd /the/root/directory
for dir in */
do
for FILE in "$dir/"*
do
echo "$FILE"
done > /the/root/directory/filenames.txt
done
uj5u.com熱心網友回復:
bash 的實作方式是globstar在目錄中遞回擴展的擴展
#!/usr/bin/env bash
shopt -s globstar # This enables recursively expanding files in directories
# This prints all the files in all the directories starting from /the/root/directory
printf '%s\n' /the/root/directory/**
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/490972.html
下一篇:保存名稱略有不同的檔案
