假设我有一些任意的多行文本文件:
sometext
moretext
lastline
如何仅删除文件的最后一个字符(e,而不是换行符或null),而不使文本文件无效?
假设我有一些任意的多行文本文件:
sometext
moretext
lastline
如何仅删除文件的最后一个字符(e,而不是换行符或null),而不使文本文件无效?
更简单的方法(outputs to stdout,不更新输入文件):
sed '$ s/.$//' somefile
$
是一个Sed地址,它只与最后一个输入行匹配,因此导致以下函数调用(s/.$//
)只在最后一行上执行.
s/.$//
replaces the last character on the (in this case last) line with an empty string; i.e., effectively removes the last char. (before the newline) on the line.
.
matches any character on the line, and following it with $
anchors the match to the end of the line; note how the use of $
in this regular expression is conceptually related, but technically distinct from the previous use of $
as a Sed address.
使用stdin输入的示例(假定为Bash、Ksh或Zsh):
$ sed '$ s/.$//' <<< $'line one\nline two'
line one
line tw
到update the input file(如果输入文件是符号链接,则不要使用):
sed -i '$ s/.$//' somefile
Note:
-i ''
而不是-i
;有关-i
的trap 概述,请参见this answer的下半部分.