仅当匹配不受字母或数字约束时,如何使用 sed 查找和替换项目? [英] How to use sed to find and replace items, only if the match is not bound by letters or numbers?

查看:45
本文介绍了仅当匹配不受字母或数字约束时,如何使用 sed 查找和替换项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sed 来查找和替换项目,例如:

I am using sed to find and replace items, e.g.:

sed -i 's/fish/bear/g' ./file.txt

我想将此限制为仅更改前后没有字母或数字的项目,例如:

I want to limit this to only change items which do not have a letter or number before or after, e.g.:

  • 鱼吃了蠕虫.会改变,因为前后只有空格.
  • 狮子鱼吃了蠕虫.不会改变,因为在fish之前有一个字母.
  • The fish ate the worm. would change, because only spaces are before and after.
  • The lionfish ate the worm. would not change, because there is a letter before fish.

我如何查找和替换某些项目,但如果前后至少出现一个字母或数字,则无法查找和替换?

How can I find and replace some items, but not if at least one letter or number appears immediately before or after?

推荐答案

fish 前后使用负字符类,像这样:\(^\|[^[:alnum:]]\)fish\($\|[^[:alnum:]]\).这说:

Use a negative character class before and after fish, like so: \(^\|[^[:alnum:]]\)fish\($\|[^[:alnum:]]\). This says:

  1. 行首或任何非字母数字
  2. 跟着鱼
  3. 后跟行尾或任何非字母数字

这保证紧接在 fish 之前和之后的字符不是字母数字.

This guarantees that the characters immediately preceding and immediately following fish are not alphanumeric.

sed 's/\(^\|[^[:alnum:]]\)fish\($\|[^[:alnum:]]\)/\1bear\2/g'

这篇关于仅当匹配不受字母或数字约束时,如何使用 sed 查找和替换项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆