利用以下事实:a)换行符在文件末尾,b)字符大小为1字节:使用truncate命令将文件缩小一个字节:
# a file with the word "test" in it,with a newline at the end (5 characters total) $cat foo test # a hex dump of foo shows the '\n' at the end (0a) $xxd -p foo 746573740a # and `stat` tells us the size of the file: 5 bytes (one for each character) $stat -c '%s' foo 5 # so we can use `truncate` to set the file size to 4 bytes instead $truncate -s 4 foo # which will remove the newline at the end $xxd -p foo 74657374 $cat foo test$
您还可以将尺寸和数学转换为一行命令:
truncate -s $(($(stat -c '%s' foo)-1)) foo