【问题标题】:Replace periods with substitution in bash script using perl except questionmark or exclamation mark使用 perl 在 bash 脚本中用替换替换句点,问号或感叹号除外
【发布时间】:2017-01-15 22:59:26
【问题描述】:

最初我想出了如何删除所有文件的句点,然后将它们添加回来:

 Remove periods at end of titles
 perl -pi -e 's/title = \{(.*)\.\},/title = \{$1\},/g' $1
 # Add periods back so all files are the same (comment out if no periods wanted)
 perl -pi -e 's/title = \{(.*)\},/title = \{$1\.\},/g' $1

理想情况下,我想做的是检查每个标题是否有句号、感叹号或问号,如果没有,则添加句号。我认为有一种简单的方法可以进行这种替换,但我不太了解语法。

例如输入:

title = This has a period.
title = This has nothing
title = This has a exclamation!
title = This has a question?

输出将是:

title = This has a period.
title = This has nothing.
title = This has a exclamation!
title = This has a question?

所以它只会在没有任何标记的情况下将行修改为有一个句点。

【问题讨论】:

  • 提供样本输入(所有可能的情况 - 结尾有/没有句点。)及其各自的输出......
  • @anishsane 已添加
  • 另外,如果最后有多个.怎么办? title = This has multiple periods...

标签: bash perl substring substitution


【解决方案1】:

KISS,使用否定字符类。

perl -pi -e 's/title = \{(.*[^.?!])\},/title = \{$1\.\},/g' $1

DEMO

或

使用消极的向后看。

perl -pi -e 's/title = \{(.*)(?<![.?!])\},/title = \{$1\.\},/g' $1

DEMO

【讨论】:

    【解决方案2】:

    你可以使用这个sed:

    sed '/^title = .*[.!?]$/!s/$/./' file
    

    (或)

    sed '/^title = .*[^.!?]$/s/$/./' file
    

    测试:

    $ sed '/^title = .*[.!?]$/!s/$/./' file
    title = This has a period.
    title = This has nothing.
    title = This has a exclamation!
    title = This has a question?
    

    【讨论】:

      猜你喜欢
      • 2015-04-09
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多