使用 perl 在 bash 脚本中替换句点,问号或感叹号除外

Replace periods with substitution in bash script using perl except questionmark or exclamation mark

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

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

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

例如输入:

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?

因此,如果行结束时没有任何标记,它只会修改带有句点的行。

KISS,使用否定字符class。

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

DEMO

使用负面回顾。

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

DEMO

你可以使用这个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?