gpt4 book ai didi

bash - 使用 sed 维护替换词的复数性和适当的大写

转载 作者:行者123 更新时间:2023-11-29 09:21:32 24 4
gpt4 key购买 nike

我意识到这个标题很可怕,但无论如何,我有一个任务要使用 sed 将所有“cat”实例更改为“dog”。很简单,但它还包括像“catapult”和“bearcat”这样的词,我试图通过在代码中放置一个空格来避免这些词。我的问题是每个词都变成了“狗”,在某些情况下我希望它是“狗”或“狗”......

这是我要更改的文本文件:

Dear Homeowner,

Cats are important to people. We all enjoy the company of cats. If you have ever wanted to own a cat we can help. We are attempting to hold a “cat comes home” day for our city. To help us we've enlisted the NWMSU Bearcat cheerleaders, the organizers of the city's annual catapult toss, and local celebrities to help find homes for cats.

There is a cat that needs you to provide a home for them. So if you are a cat lover, please come and see if there isn't some way to find a home in your heart for a cat.

Thanks!!

Cats are people too.

这是我得到的明显错误的输出

Dear Homeowner,

dog are important to people. We all enjoy the company of cats. If you have ever wanted to own a cat we can help. We are attempting to hold a “cat comes home” day for our city. To help us we've enlisted the NWMSU Bearcat cheerleaders, the organizers of the city's annual catapult toss, and local celebrities to help find homes for cats.

There is a cat that needs you to provide a home for them. So if you are a cat lover, please come and see if there isn't some way to find a home in your heart for a cat.

Thanks!!

dog are people too.

这是我的代码:

sed 's/[Cc]at[s] /dog /g' cats-dogs.txt 

最佳答案

我很确定您不能单独在(单个)RegEx 中执行此操作。

也就是说,这里的简单解决方案可能是最好的,因为似乎只有两种可能的情况(大写和小写)和一个替换词(而且 sed 允许轻松进行多个替换)。

所以像这样的东西应该可以工作(假设 GNU sed):

sed -r 's/\bCat(s?)\b/Dog\1/g; s/\bcat(s?)\b/dog\1/g' cats-dogs.txt

使用扩展的正则表达式,因为在命令行中引用它远没有那么可怕。也请注意此处的单词边界扫描。

可能有一种非常聪明(但不可读)的 sed 方法可以使用 \u 和缓冲区来做到这一点..

关于bash - 使用 sed 维护替换词的复数性和适当的大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29526457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com