How can I delete a newline if it is the last chara

2019-01-03 21:58发布

I have some files that I'd like to delete the last newline if it is the last character in a file. od -c shows me that the command I run does write the file with a trailing new line:

0013600   n   t  >  \n

I've tried a few tricks with sed but the best I could think of isn't doing the trick:

sed -e '$s/\(.*\)\n$/\1/' abc

Any ideas how to do this?

22条回答
一纸荒年 Trace。
2楼-- · 2019-01-03 22:59

A very simple method for single-line files, requiring GNU echo from coreutils:

/bin/echo -n $(cat $file)
查看更多
看我几分像从前
3楼-- · 2019-01-03 23:00
sed ':a;/^\n*$/{$d;N;};/\n$/ba' file
查看更多
smile是对你的礼貌
4楼-- · 2019-01-03 23:02

gawk

   awk '{q=p;p=$0}NR>1{print q}END{ORS = ""; print p}' file
查看更多
We Are One
5楼-- · 2019-01-03 23:03

A fast solution is using the gnu utility truncate:

[ -z $(tail -c1 file) ] && truncate -s-1

The test will be true if the file does have a trailing new line.

The removal is very fast, truly in place, no new file is needed and the search is also reading from the end just one byte (tail -c1).

查看更多
登录 后发表回答