sed - 移除行末的句点

7

我正在尝试删除文本文件中行末的句号。有些行末有句号,而有些则没有:

$cat textfile
sometexthere.123..22.no_period
moretext_with_period.  **<-- remove this period**
no_period_here_either
period.   **<-- remove this period**

我尝试过这个方法,但好像并不起作用:
sed 's/\.$//g' textfile > textfile2

(GNU sed 版本4.2.1)
谢谢。

可能会很有启发性,看一下 $ cat -vet textfile 的输出。 - MetaEd
1
你为什么要使用 g 修饰符? - MetaEd
4个回答

8

虽然这只是一个猜测,但我之前在尝试混合Windows文件和Linux文件时遇到过类似的问题。Windows会在每个换行符(除了标准的\n)后添加额外的\r字符。你尝试使用dos2unix工具了吗?

[user@localhost ~]$ cat testfile
abc
def.
[user@localhost ~]$ sed 's/\.$//g' testfile
abc
def.
[user@localhost ~]$ dos2unix testfile
dos2unix: converting file testfile to UNIX format ...
[user@localhost ~]$ sed 's/\.$//g' testfile
abc
def
[user@localhost ~]$ 

示例 -
[user@localhost ~]$ cat temp.txt 
this is a text created on windows
I will send this to unix
and do cat command.

[user@localhost ~]$ cat -v temp.txt 
this is a text created on windows^M
I will send this to unix^M
and do cat command. 

这似乎有效。dos2unix似乎对文件进行了“某些”处理,以便sed 's/.$//g'命令现在可以正常工作...dos2unix实际上做了什么呢? 如果有人想知道,我的文本文件是非常大的csv文件中的一列。 - user559555
2
在Linux文件的每行末尾都有\n,但在Windows文件的每行末尾都是\r\n。你的正则表达式没有匹配成功,因为句号不是直接跟在\n后面(\r挡住了路)。 - Thomas Kelley
1
我在这个解决方案中添加了一个示例。一旦它被审核,您应该能够看到它。如果您注意到这样的异常,检查的好方法是执行 cat -v filename 命令。这将显示所有非打印字符,以便它们可见。 - jaypal singh
1
@Jaypal:如果你有支持的版本,cat -A filename会更好。除了以可打印的格式显示非打印字符外,它还将制表符替换为^I并在每行末尾添加$ - Keith Thompson
cat -vet filename,其中 -A 选项不可用。 :) - jaypal singh

4
如果你需要一个单独的sed命令来完成此操作,而不使用会更改原始文件的dos2unix,你可以像这样做(可能需要GNU sed)。
sed -E 's/\.(^M?)/\1/' testfile

您可以在命令行中使用键盘组合键Ctrl+V,然后再按Ctrl+M来输入^M

这将删除一个句点(.),可选地跟随一个回车符号,并且如果原始文本中存在回车符号,则会替换该回车符号。


1

sed 's/period[.| ]*$//g' ts.txt > ts1.txt

输入文件: sometexthere.123..22.no_period moretext_with_period.
no_period_here_either period.

输出文件: sometexthere.123..22.no_ moretext_with_ no_period_here_either


1
sed -r 's/\.$//'

这也适用于删除最后一个句号。

我相信你有一个冗余的'' sed -r 's/.$//' 对我有用。 - ishamdo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接