删除文件末尾的换行符

问题描述 投票:20回答:5

要删除所有换行,请说:

tr -d '\n' < days.txt
cat days.txt | tr -d '\n'

但是你如何使用tr删除文本文件末尾的新行呢?

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

bash scripting newline tr
5个回答
24
投票

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

36
投票

比公认的解决方案更简单的解决方案:

truncate -s -1 <<file>>

从截断手册页:

-s, --size=SIZE
    set or adjust the file size by SIZE
SIZE may also be prefixed by one of the following modifying characters:
    '+' extend by, '-' reduce by, '<' at most, '>' at least, '/' round down
    to multiple of, '%' round up to multiple of.

19
投票

如果您确定最后一个字符是换行符,则非常简单:

head -c -1 days.txt

head -c -N表示除最后N个字节之外的所有内容


12
投票

我认为你最好的选择是Perl:

perl -0pe 's/\n\Z//' days.txt

-0使perl将整个文件视为一个大字符串。 -p告诉它在运行程序后打印出该字符串。 -e说“这是运行的程序”。

正则表达式\n\Z匹配换行符,但前提是它是字符串中的最后一个字符。并且s/\n\Z//说完全没有替换这样的换行符,删除它。

上面的命令输出文件的新版本,但您可以通过添加-i(“就地”)选项来修改现有版本,可选择使用后缀,该后缀将在修改之前用于命名文件的备份副本它:

 perl -i.bak -0pe 's/\n\Z//' days.txt

这个解决方案是安全的,因为如果最后一个字符不是换行符,则不会被触及。其他解决方案只是删除最后一个字节,无论什么可能会破坏这样的文件。


6
投票

试试这个命令:sed '$ { /^$/ d}' days.txt

您可以将其读作:“检查最后一行是否为空行。如果是,请删除此行”。我测试了两种情况:首先是一个文件在末尾有一个新行,另一个文件以一个以其他东西结尾的文件。

© www.soinside.com 2019 - 2024. All rights reserved.