我怎样才能删除UNIX文件的最后一个字符? [英] How can I remove the last character of a file in unix?
问题描述
说我有一些任意多行文本文件:
Say I have some arbitrary multi-line text file:
sometext
moretext
lastline
我
如何只能删除该文件的最后一个字符(即不换行或空)未做文本文件无效?
How can I remove only the last character (the e, not the newline or null) of the file without making the text file invalid?
推荐答案
一个更简单的方法(输出到stdout 的,不更新输入文件):
A simpler approach (outputs to stdout, doesn't update the input file):
sed '$ s/.$//' somefile
-
$
是最后输入行只匹配,从而导致下面的函数调用(取值/.$//一个桑达地址code>)到最后一行只执行。
-
取值/.$//
替换上的最后一个字符(在本例中的最后的),用一个空字符串行;即,有效地消除了最后一个字符。 (前行)就行了。结果
。
比赛线路上的任何字符,并以$
其后停靠比赛的结束线;注意如何在此的常规EX pression使用$
的是概念上相关的,但是从previous利用技术上不同的$
作为桑达的地址的 -
例:标准输入的输入(假设猛砸,ksh或岩组):
$
is a Sed address that matches the last input line only, thus causing the following function call (s/.$//
) to be executed on the last line only.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.Example with stdin input (assumes Bash, Ksh, or Zsh):
$ sed '$ s/.$//' <<< $'line one\nline two' line one line tw
要的更新输入文件的太(不如果输入文件是一个符号链接使用):
To update the input file too (do not use if the input file is a symlink):
sed -i '$ s/.$//' somefile
注:在OSX,你必须使用 -i''
而不仅仅是 -i $ C $的C>。结果
对于 -i
相关的缺陷概述,请参阅我回答这里。
Note: On OSX, you'd have to use -i ''
instead of just -i
.
For an overview of the pitfalls associated with -i
, see the bottom half of my answer here.
这篇关于我怎样才能删除UNIX文件的最后一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!