2014/08/01

Shell script: 計算檔案行數 (Count how many lines in a file)


[ Quick Solution Mode ]
$ cat test.log
aaaaa
bbbbb
ccccc
ddddd

# Way I
$ wc -l ./test.log         # -l, --lines: print the newline counts
4 ./test.log

# Way II
$ grep -c '' ./test.log    # -c, --count: print a count of matching lines
4

# Way III
$ sed -n '$=' ./test.log   # $: match last line, =:print current line number
4


[ Verbose Mode ]
由以上三種方法可以看出用 grep 或 sed 時只會回傳總行數,
如果需要用行數來做一些處理時就會比用 wc 來的方便

sed 的 -n 指的是 silent (安靜模式),
表示只顯示匹配的結果,
若不加就會將檔案內容也給輸出了,
所以通常使用 sed 時都會加上 -n 的參數



沒有留言:

張貼留言