for term in `cat stopwords`; do sed -i 's/\<$term\>//g' spam.txt ;done
Run Code Online (Sandbox Code Playgroud)
鉴于停用词每行包含一个单词而spam.txt是纯文本文件,我只需要替换停用词的完全匹配.不按我的预期行事......请注意doesn't,couldn't两个文件中都有类似的字样.
小智 8
你确定要在for循环中运行sed吗?我会使用sed脚本文件.
TMPFILE=mktemp
for WORD in $(cat stopwords); do echo 's/'$WORD'//g' >> $TMPFILE; done
sed -f $TMPFILE spam.txt
rm -f $TMPFILE
Run Code Online (Sandbox Code Playgroud)
那么你应该在你的sed命令中使用"而不是'.使用单引号'告诉shell不要替换$ term.
这个 :
for term in `cat stopwords`; do sed -i "s/\<$term\>//g" spam.txt ;done
Run Code Online (Sandbox Code Playgroud)
效劳于 :
# stopwords
couldn't
Run Code Online (Sandbox Code Playgroud)
并且:
# spam.txt
foo <couldn't> bar
Run Code Online (Sandbox Code Playgroud)
我的2美分