Reputation: 1506
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
Upvotes: 0
Views: 1953
Reputation: 4043
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'. \w*
should work. \w
actually matched [a-zA-Z0-9_]
\s
should be added.Upvotes: 2
Reputation: 133538
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
Upvotes: 0