2016-11-11 69 views
0

我是bash的新手,我試圖cd到父目錄的所有子目錄,並在這些子目錄包含的所有文件中執行命令。但它不工作。shell-script -cd在一個目錄的所有子目錄中,對它們的文件執行命令

for subdir in $parentdirectory 
do 
    for file in $subdir 
    do 
    ngram - lm somefilename.lm - ppl file 
    done 
done 
+0

你是否試圖以特定的順序走過一個目錄,或者你只是想確保程序在每個級別執行? –

+0

我想在每個級別執行。 – user3606057

回答

0

有很多方法可以做到這一點,但需要您明確地切換到該目錄。假設$parentdirectory正確初始化,那麼你可以看看這樣的:

for subdir in ${parentdirectory} 
do 
    cd ${subdir}  # go into the subdir 
    for file in * # glob expansion 
    do 
     ngram - lm somefilename.lm - ppl ${file} 
    done 
    cd ..   # go back up 
done 

也可以看看在一流的高級Bash腳本編程指南:http://tldp.org/LDP/abs/html/loops1.html

0

如果你想用小做到這一點空間量,你可以使用find -exec來做一些事情。

如:

# add a file called foo into every subdirectory find . -type d -exec sh -c 'touch "$0/foo"' {} \;

或者,如果你想呼應字符串到每個剛剛創建這些文件的:

# find all files and append 'ABC' into them find . -type f -exec sh -c 'echo "ABC" >> $0' {} \;

find -exec組合是一個非常強大工具,可以節省您一些目錄/文件導航,並允許您實現它所期望的功能,而無需播放下降/提升目錄結構。另外,正如你大概猜測的那樣,如果你不小心,這種事情會變得非常糟糕,所以請謹慎使用。

相關問題