How To Sed Search Replace Entire Word With String

2019-08-17 23:51发布

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

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?

Example:

Input:

Here Is My Example Testing Code

File.txt:

example
test

Desired output:

Here Is My Code

2条回答
何必那么认真
2楼-- · 2019-08-18 00:29

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

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

Brief explanation,

  • \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.
查看更多
等我变得足够好
3楼-- · 2019-08-18 00:55

Following awk could help you in same.

awk 'FNR==NR{a[$0]=$0;next} {for(i=1;i<=NF;i++){for(j in a){if(tolower($i)~ a[j]){$i=""}}}} 1' file.txt input
***OR***
awk '
FNR==NR{
  a[$0]=$0;
  next
}
{
for(i=1;i<=NF;i++){
  for(j in a){
    if(tolower($i)~ a[j]){
     $i=""}
}}}
1
' file.txt input

Output will be as follows.

Here Is My   Code

Also if your Input_file is always a single space delimited and you don't want unnecessary space as shown in above output, then you could use following.

awk 'FNR==NR{a[$0]=$0;next} {for(i=1;i<=NF;i++){for(j in a){if(tolower($i)~ a[j]){$i=""}}};gsub(/ +/," ")} 1' file.txt input
***OR***
awk '
FNR==NR{
a[$0]=$0;
next
}
{
for(i=1;i<=NF;i++){
 for(j in a){
   if(tolower($i)~ a[j]){
    $i=""}
}};
gsub(/ +/," ")
}
1
' file.txt input

Output will be as follows.

Here Is My Code
查看更多
登录 后发表回答