删除文件末尾的换行符

22 bash scripting newline tr

要删除所有换行,请说:

tr -d '\n' < days.txt
cat days.txt | tr -d '\n'
Run Code Online (Sandbox Code Playgroud)

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

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

Chr*_*ard 37

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

truncate -s -1 <<file>>
Run Code Online (Sandbox Code Playgroud)

从截断手册页:

-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.
Run Code Online (Sandbox Code Playgroud)


Chr*_*lan 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$ 
Run Code Online (Sandbox Code Playgroud)

您还可以将大小调整和数学滚动到一行命令中:

truncate -s $(($(stat -c '%s' foo)-1)) foo
Run Code Online (Sandbox Code Playgroud)


Raú*_*udo 20

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

head -c -1 days.txt
Run Code Online (Sandbox Code Playgroud)

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

  • 在OS X优胜美地10.10.5得到`head:非法字节数 - -1` :( (10认同)

Mar*_*eed 12

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

perl -0pe 's/\n\Z//' days.txt
Run Code Online (Sandbox Code Playgroud)

-0perl 的原因是将整个文件视为一个大字符串.该-p告诉它打印字符串返回出来就可以运行该程序后.并-e说"这是运行的程序".

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

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

 perl -i.bak -0pe 's/\n\Z//' days.txt
Run Code Online (Sandbox Code Playgroud)

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


Lyn*_*nch 7

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

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

  • 使用`sed`的就地模式更好:sed -i'$ {/ ^ $/d}'days.txt (2认同)

Enr*_*lis 6

另一个 Sed 解决方案:

sed -z s/.$// days.txt
Run Code Online (Sandbox Code Playgroud)

-z选项是将文件解释为单个长字符串(换行符嵌入为\n),然后匹配行尾(= 文件结尾)之前的s单个字符,并将其更改为空。无需引用该命令。.$

如果您不确定最后一个字符是换行符,那么您可以执行以下任一操作:

sed -z s/\\n$// days.txt
sed -z 's/\n$//' days.txt
Run Code Online (Sandbox Code Playgroud)