歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell中的trailing newline

shell中的trailing newline

日期:2017/3/1 10:14:25   编辑:SHELL編程

最近在學shell腳本,發現很多的shell命令都涉及到一個trailing newline的東西,例如wc -l。

man wc,找到-l發現解釋如下:

print the newline counts

即打印出newline 的個數,那newline 到底是什麼東西呢?翻了翻詞典,發現是結尾換行符的意思,那是不是結尾的時候按下回車的時候產生的換行符呢?

在百度搜索資料,發現了一篇文章,原來“很多軟件或命令都會自動加上一個trailing newline,也就是c語言裡的\n,ascii碼為10”。

自己動手驗證下:

#vi test

輸入如下內容 :

abcd 1234

#wc -l test,

發現返回值為1.

#vi test2

輸入如下內容:

abcd

1234

#wc -l test2

而這次的返回值變成了2!。兩次的內容的唯一的差別就是我多敲了一個回車,而wc -l選項是統計newline即回車符的個數的,所以才會導致兩次的結果變化。

寫到這裡忽然想起來一個疑問:

#ls

Desktop examples.desktop hello.c nus Public test
Documents fcitx-4.0.0 helloword nusers t Ubuntu One
Downloads fcitx-4.0.0.tar.gz Music Pictures Templates Videos

#ls | wc -l

18

問題來了,為什麼返回值是18?ls返回的結果只有三行,不是應該有三個換行符嗎?那接過應該是3呀。

#ls > t

#cat t

Desktop
Documents
Downloads
examples.desktop
fcitx-4.0.0
fcitx-4.0.0.tar.gz
hello.c
helloword
Music
nus
nusers
Pictures
Public
t
Templates
test
Ubuntu One
Videos

我把輸入重定向之後發現每一個字符後面都跟有一個換行符,應該是ls命令在每個字符的後面都有跟著換行符來分割字符,只是輸出到終端的時候刪掉了一部分。

Copyright © Linux教程網 All Rights Reserved