如何sed搜索将整个单词替换为文件中的字符串匹配 [英] How To Sed Search Replace Entire Word With String Match In File

查看:728
本文介绍了如何sed搜索将整个单词替换为文件中的字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我修改了此处找到的代码: sed全字搜索并替换

I have modified the code found here: sed whole word search and replace

我一直在尝试对sed使用正确的语法\<\>来匹配文件中的多个术语.

I have been trying to use the proper syntax \< and \> for the sed to match multiple terms in a file.

echo "Here Is My Example Testing Code" | sed -e "$(sed 's:\<.*\>:s/&//ig:' file.txt)"

但是,我认为,因为它正在查看文件,所以它与完整单词(仅完全匹配)不匹配,只剩下一些拆分单词和单个字符.

However, I think, because it's looking into the file, it doesn't match the full word (only exact match) leaving some split words and single characters.

有人知道正确的语法吗?

Does anyone know the proper syntax?

示例:

输入:

Here Is My Example Testing Code

File.txt:

example
test

所需的输出:

Here Is My Code

推荐答案

按如下所示修改您的sed命令应提取您想要的内容,

Modify your sed command as followed should extract what you want,

sed -e "$(sed 's:\<.*\>:s/&\\w*\\s//ig:' file.txt)"

简要说明,

  • \b匹配单词和非字母数字字符之间的位置.在这种情况下,file.txt中的模式"test"将与"Testing"不匹配.
  • 通过这种方式,修改附加了\w*的搜索模式应该可以. \w实际上与[a-zA-Z0-9_]
  • 相匹配
  • 并且不要忘记消除每个搜索模式后面的空间,应添加\s.
  • \b matches the position between a word and a non-alphanumeric character. In this case, the pattern 'test' in file.txt would not match 'Testing'.
  • In this way, modify the searched pattern appended with \w* should work. \w actually matched [a-zA-Z0-9_]
  • And don't forget to eliminate the space behind each searched pattern, \s should be added.

这篇关于如何sed搜索将整个单词替换为文件中的字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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