Bash技巧:把變量賦值為換行符(判斷文件是否以換行符結(jié)尾)
變量賦值為換行符
在 bash 中,如果要把變量賦值為換行符,寫為 '\n' 沒有效果,需要寫為 $'\n'。具體舉例如下:
$ newline='\n' $ echo $newline \n $ newline=$'\n' $ echo $newline
可以看到,把 newline 變量賦值為 'n',得到的是 n 這個(gè)字符串,而不是換行符自身。
這是 bash 和 C 語言不一樣的地方。
在 C 語言中,'n' 對應(yīng)換行符自身,只有一個(gè)字符;而 "n" 對應(yīng)一個(gè)字符串。
但是在 bash 中,'n' 也是對應(yīng)一個(gè)字符串。
把 newline 賦值為 $'\n',就能獲取到換行符自身。查看 man bash 對這個(gè)寫法的說明如下:
Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:
\n new line \r carriage return \t horizontal tab \' single quote
The expanded result is single-quoted, as if the dollar sign had not been present.
即,$'string' 這個(gè)寫法可以使用 C 語言的轉(zhuǎn)義字符來獲取到對應(yīng)的字符自身。
判斷文件的最后一行是否以換行符結(jié)尾
在 Linux 中,可以使用下面命令來判斷文件的最后一行是否以換行符結(jié)尾:
test -n "$(tail filename -c 1)"
這里使用 tail filename -c 1 命令獲取到 filename 文件的最后一個(gè)字符。
實(shí)際使用時(shí),需要把 filename 換成具體要判斷的文件名。
tail 命令可以獲取文件末尾的內(nèi)容。它的 -c 選項(xiàng)指定要獲取文件末尾的多少個(gè)字節(jié)。
查看 man tail 對 -c 選項(xiàng)的說明如下:
-c, --bytes=K
output the last K bytes; alternatively, use -c +K to output bytes starting with the Kth of each file.
即,tail -c 1 命令指定獲取所給文件的最后一個(gè)字符。
獲取到文件的最后一個(gè)字符后,要判斷該字符是不是換行符。這里不能直接判斷該字符是否等于換行符,而是要判斷該字符是否為空。
原因在于,使用 $(tail filename -c 1) 命令替換來獲取內(nèi)部命令的輸出結(jié)果時(shí),bash 會去掉末尾的換行符。
所以當(dāng)文件的最后一行以換行符結(jié)尾時(shí),$(tail filename -c 1) 命令替換會去掉獲取到的換行符,最終結(jié)果為空,并不會返回?fù)Q行符自身。
查看 man bash 對命令替換(command substitution)的說明如下:
Command substitution allows the output of a command to replace the command name. There are two forms:
$(command) or `command`
Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.
可以看到,經(jīng)過命令替換后,會去掉末尾的換行符。
由于 $(tail filename -c 1) 命令替換會去掉末尾的換行符,這里使用 test -n 來判斷最終結(jié)果是否為空字符串。
如果文件最后一行以換行符結(jié)尾,那么 $(tail filename -c 1) 的結(jié)果為空,test -n 命令會返回 1,也就是 false。
如果文件最后一行沒有以換行符結(jié)尾,那么 $(tail filename -c 1) 的結(jié)果不為空,test -n 命令會返回 0,也就是 true。
可以根據(jù)實(shí)際需要,改用 test -z 來判斷。如果文件最后一行以換行符結(jié)尾,$(tail filename -c 1) 的結(jié)果為空,test -z 命令會返回 0,也就是 true。
到此這篇關(guān)于Bash技巧:把變量賦值為換行符,判斷文件是否以換行符結(jié)尾的文章就介紹到這了,更多相關(guān)變量賦值為換行符內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一天一個(gè)shell命令 linux好管家-進(jìn)程-ps命令詳解
這篇文章主要介紹了一天一個(gè)shell命令 linux好管家-進(jìn)程-ps命令詳解 ,需要的朋友可以參考下2016-06-06
linux 使用NSF 映射遠(yuǎn)程磁盤目錄的實(shí)現(xiàn)
下面小編就為大家?guī)硪黄猯inux 使用NSF 映射遠(yuǎn)程磁盤目錄的實(shí)現(xiàn)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02
shell耗時(shí)計(jì)算的實(shí)現(xiàn)
本文主要介紹了shell耗時(shí)計(jì)算的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

