我如何限制查找和替换以替换项目,但如果紧接在它之前的字符是“A”,“B”或“C”或紧跟在它之后的字符是“X”,“Y”,或“Z”。例如。给定这些输入行,如果要用“pet”替换“cat”:
答案 0 :(得分:4)
这个sed应该适合你:
sed -r 's/(^|[^ABC])cat\>/\1pet/g; s/\<cat([^XYZ]|$)/pet\1/g' file
<强>测试强>
sed -r 's/(^|[^ABC])cat\>/\1pet/g; s/\<cat([^XYZ]|$)/pet\1/g' <<< 'cat is a cat is a cat'
pet is a pet is a pet
答案 1 :(得分:3)
这可能适合你(GNU sed):
sed 's/\bcat\b/pet/g' file
或:
sed 's/\<cat\>/pet/g' file
或根据评论:
sed -r 's/(\b|[^ABC])cat(\b|[^XYZ])/\1pet\2/g' file
答案 2 :(得分:2)
假设您的文字位于名为text.txt
的文件中。这将有效:
sed -i 's/\(.*[^ABC]\|^\)cat\([^XYZ].*\|$\)/\1pet\2/g' text.txt
发生了什么(来自tutorialspoint.com,man sed和sed regex):
-i Edit files in place (makes backup if extension supplied)
s/???/???/ Or s/regexp/replacement/, Attempt to match regexp against the pattern space.
/ Field separator to 's'.
^ Match first character on line.
\( Start back reference.
. Match any character.
[^ABC] Do not match any charcter (^ = don't) in this list.
\| Matches regex1 or regexp2 (do not match ABC or match start of line).
\) End back reference.
cat Match cat
\1 The first back reference.
\2 The second back reference.
g Replace all matches, not just the first match.
答案 3 :(得分:0)
使用perl可能是一个更好的主意,因为它支持前瞻/后瞻:
perl -lape 's/(?<![ABC])cat(?![XYZ])/pet/' input