如何限制查找和替换以替换项目,但不替换前面紧跟着"A"、"B"或"C"或后面紧跟着"X"、"Y"或"Z"的字符。例如,给定以下输入行,如果要用"pet"替换"cat":
- "There is a cat." → "These is a pet."
- "There is Acat." 不变,因为在前面找到了"A"。
- "There is catY." 不变,因为在后面找到了"Y"。
- "There is CcatX." 不变,因为在前面找到了"C"并且在后面找到了"X"。
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
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
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.
cat is a cat
进行测试 - anubhava
猫是猫是猫
。 - cforbishpet is a pet is a pet
。 - anubhava宠物是猫是宠物
。不过我还是给你点了个赞。 - cforbish