加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 删除文件末尾的换行符

发布时间:2020-12-15 18:46:26 所属栏目:安全 来源:网络整理
导读:要删除所有换行符,可以说: tr -d 'n' days.txtcat days.txt | tr -d 'n' 但是如何使用tr只删除文本文件末尾的换行符? 我不确定只指定最后一个. 利用以下事实:a)换行符在文件末尾,b)字符大小为1字节:使用truncate命令将文件缩小一个字节: # a file wit
要删除所有换行符,可以说:
tr -d 'n' < days.txt
cat days.txt | tr -d 'n'

但是如何使用tr只删除文本文件末尾的换行符?

我不确定只指定最后一个.

利用以下事实: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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读