我如何限制查找和替换以替换项目,但如果紧接在它之前的字符是"A","B"或"C"或紧跟在它之后的字符是"X","Y"或"Z"则不能".例如,给定这些输入行,如果要用"pet"替换"cat"替换:
假设您的文本位于名为text.txt. 这将起作用:
sed -i 's/\(.*[^ABC]\|^\)cat\([^XYZ].*\|$\)/\1pet\2/g' text.txt
Run Code Online (Sandbox Code Playgroud)
发生了什么(来自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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3450 次 |
| 最近记录: |