2012-12-05 54 views
29

如何計算wc的所有子目錄中的所有文件的所有行?在所有子目錄中使用wc來計算行數

cd mydir 
wc -l * 
.. 
11723 total 

man wc表明wc -l --files0-from=-,但我不知道如何生成的所有文件的列表作爲NUL-terminated names

find . -print | wc -l --files0-from=- 

沒有工作。

+3

'find。 -name'*'| xargs wc -l'可能會有所幫助。 – axiom

回答

63

你可能想這樣的:

find . -type f -print0 | wc -l --files0-from=- 

如果只想線路總數,你可以使用

find . -type f -exec cat {} + | wc -l 
+3

無用的貓使用 –

+6

@ДМИТРИЙМАЛИКОВ爲什麼? –

+5

我用'find。 -type f -print0 | wc -l --files0-from = -'它工作正常,並在最後返回總和。 –

0

我建議像

find ./ -type f | xargs wc -l | cut -c 1-8 | awk '{total += $1} END {print total}' 
+0

'-not -type d'? –

+0

所有不是目錄;在大多數情況下,將與-type f – sge

+2

相同除了塊設備節點,字符設備節點,命名管道,套接字......至少其中之一將打破整個練習...最好堅持'鍵入f' ... – twalberg

6

也許你正在尋找findexec選項。

find . -type f -exec wc -l {} \; | awk '{total += $1} END {print total}' 
+2

這是效率低下的,因爲你正在爲每個文件產生一個新的'wc'。 ':-(' –

+3

也是這樣,如果你碰巧有這樣一個文件,就完全破壞了:嘗試'touch $'hello \ n1000000''。驚喜! –

-1

有點晚了這裏的比賽,但不會這也工作? find . -type f | wc -l

這將統計'find'命令輸出的所有行。您可以微調「查找」以顯示您想要的任何內容。我使用它來計算深樹中一個特定子目錄中子目錄的數量:find ./*/*/*/*/*/*/TOC -type d | wc -l。輸出:76435。 (只是做了發現沒有所有的干預星號產生一個錯誤。)

+1

不,我認爲這會返回類似文件數量的東西。不是所有文件中所有行的總和。 –

+0

啊,現在看。是的,不,它不會。 :) – Cronk

4

要計算特定的文件擴展名u可以使用所有線路,

find . -name '*.fileextension' | xargs wc -l 

如果你想在兩個或兩個以上不同類型的文件ü可以把-o選項

find . -name '*.fileextension1' -o -name '*.fileextension2' | xargs wc -l 
+2

這打破了任何文件的名稱中帶有空格或'\'的情況。請參閱[接受的答案](http://stackoverflow.com/a/13728131/1081936)瞭解如何正確使用此方法。 – terdon

2

另一種選擇是使用遞歸的grep:

grep -hRc '' . | awk '{k+=$1}END{print k}' 

awk簡單地添加數字。使用的grep選項有:

-c, --count 
      Suppress normal output; instead print a count of matching lines 
      for each input file. With the -v, --invert-match option (see 
      below), count non-matching lines. (-c is specified by POSIX.) 
    -h, --no-filename 
      Suppress the prefixing of file names on output. This is the 
      default when there is only one file (or only standard input) to 
      search. 
    -R, --dereference-recursive 
      Read all files under each directory, recursively. Follow all 
      symbolic links, unlike -r. 

grep,因此,計算匹配任何東西(「」)的行數,所以本質上只是計數線。

相關問題