gpt4 book ai didi

regex - 如何在正则表达式中允许\b 替换 sed 命令

转载 作者:行者123 更新时间:2023-12-02 08:27:25 24 4
gpt4 key购买 nike

我有一个文本文件 temp.txt 包含

Hello World
My name is MayukhSarkar
My name is mayukh
My name is MAYUKH
My name is MaYuKh
My name is mAyUkH

sed 命令

sed 's/\b[M,m][A,a][Y,y][U,u][K,k][H,h]\b/sobo/g' temp.txt

没有用 sobo 替换出现的 Mayukh

但是没有 \b 的 sed 命令是有效的

sed 's/[M,m][A,a][Y,y][U,u][K,k][H,h]/sobo/g' temp.txt

但它也将 MayukhSarkar 替换为 soboSarkar

最佳答案

$ sed -r 's/(^|[^[:alnum:]])[Mm][Aa][Yy][Uu][Kk][Hh]([^[:alnum:]]|$)/\1sobo\2/' file
Hello World
My name is MayukhSarkar
My name is sobo
My name is sobo
My name is sobo
My name is sobo

或者您似乎在使用 Bedrock sed:

sed 's/\(^\|[^[:alnum:]]\)[Mm][Aa][Yy][Uu][Kk][Hh]\([^[:alnum:]]\|$\)/\1sobo\2/'
file

使用 GNU sed:

$ sed 's/\bmayukh\b/sobo/i' file                   
Hello World
My name is MayukhSarkar
My name is sobo
My name is sobo
My name is sobo
My name is sobo

使用 GNU awk:

$ awk 'BEGIN{IGNORECASE=1} {sub(/\<mayukh\>/,"sobo")} 1' file                
Hello World
My name is MayukhSarkar
My name is sobo
My name is sobo
My name is sobo
My name is sobo

使用任何 awk:

$ awk 'match(tolower($0),/(^|[[:space:]])mayukh([[:space:]]|$)/) { tgt = substr($0,RSTART,RLENGTH); sub(/[^[:space:]]+/,"sobo",tgt); $0 = substr($0,1,RSTART-1) tgt substr($0,RSTART+RLENGTH)} 1' file
Hello World
My name is MayukhSarkar
My name is sobo
My name is sobo
My name is sobo
My name is sobo

关于regex - 如何在正则表达式中允许\b 替换 sed 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30809659/

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