2014-04-09 40 views
0

我有一個目錄結構是這樣的:如何在Linux中的子文件夾中回顯內容到每個文件?

/posts 
| 
| 
posts/page1 -- index.html 
posts/page2 -- index.html 
posts/page{3..100} -- index.html 

我已經想通了如何創建100個不同page#目錄,我已經感動index.html他們每個人。但是,我需要在page#目錄中的每個index.html文件中回顯一些基本HTML。

for f in `find . -type d`; do echo "hello" >> f; done 

但這一切確實是回聲100 hello s到一個名爲f

for f in `find . -type d`; do echo "hello"; done 

只是回聲hello 100次文件。

for f in `find . -type d`; do echo "hello" >> index.html; done 

只是回聲內posts/index.html

hello 100次,無論如何,我不知如何做到這一點。我如何做到這一點,而不必手動做到這一點?理論上,我可以在Sublime中打開每個文件夾,然後複製HTML,然後爲每個實例複製Ctrl+V + Ctrl+S + Ctrl+W,但是要做到這一點要容易得多。

回答

1

您只需使用$f即可將find結果中的項目,而不是f。而且還包括/index.html的路徑:

for f in $(find . -type d); do echo "hello" >> $f/index.html; done 
               ^^^^^^^^^^^^^ 

在你當前的代碼你重定向到恆f,而要參考的變量名稱$f。這就是使用$f而不是f的原因。

+1

啊,發現。謝謝fedorqui! 只要我被允許,我會盡快選擇你作爲正確的答案。再次感謝。 - Eric –

1
> for f in `find . -type d`; do echo "hello" >> index.html; done 

命令替換受字拆分和路徑名擴展(globbing)的限制。這在文件名包含空格(和/或通配符)時失敗。無論是集IFS到一個換行符(IFS = $「\ n」),並且禁止路徑擴展(設-f)(注:這仍然會失敗,如果文件名包含換行符),或使用發現的-exec:

find . -type d -exec sh -c 'for dir in "[email protected]" ; do echo "hello" >> "$dir/index.html" ; done' sh {} + 
相關問題