【问题标题】:sed - remove period at end of linesed - 删除行尾的句点
【发布时间】:2020-04-27 02:51:02
【问题描述】:

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

$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 的输出可能会有启发。
  • 你为什么使用g修饰符?

标签: regex sed


【解决方案1】:

这是在黑暗中拍摄的,但我之前尝试将 Windows 文件与 Linux 文件混合时遇到了这个问题。 Windows 在每个换行符处添加了一个额外的\r(除了标准的\n)您是否尝试过使用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 文件中的一列,以防人们想知道。
  • Linux 文件每一行的末尾是\n,但Windows 文件每一行的末尾是\r\n。您的正则表达式不匹配,因为句点不在 \n 旁边(\r 挡住了路)。
  • 我在这个解决方案中添加了一个示例。一旦它被审查,你应该能够看到它。如果您注意到此类异常,检查的一个好方法是发送cat -v filename。这将显示所有非打印字符,以便它们可见。
  • @Jaypal:cat -A filename,如果您有支持它的cat 版本,那就更好了。除了以可打印格式显示不可打印字符外,它还用^I 替换制表符,并在每行末尾添加$
  • cat -vet filename 其中-A 选项不可用。 :)
【解决方案2】:

如果您需要一个 sed 命令来执行此操作,而不使用 dos2unix,它会更改原始文件,您可以执行类似的操作(可能需要 GNU sed)

sed -E 's/\.(^M?)/\1/' testfile

您在命令行中键入^MCtrl+V 后跟 Ctrl+M .

这将删除一个“.”,可选地后跟一个回车字符,并替换原始中存在的 CR。

【讨论】:

    【解决方案3】:

    sed 的/句点[.| ]*$//g' ts.txt > ts1.txt

    输入文件: sometexthere.123..22.no_period moretext_with_period。
    no_period_here_either 时期。

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

    【讨论】:

      【解决方案4】:
      sed -r 's/\.$//'
      

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

      【讨论】:

      • 我相信你有一个多余的 '\' sed -r 's/\.$//' 为我工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 2018-04-11
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      相关资源
      最近更新 更多