执行不区分大小写的搜索和删除

默认情况下使用以下语法执行搜索和删除

# sed -e '/two/d' /tmp/file
one
Two
three
Three
One

要对所有单词“two”执行相同的操作,无论大小写如何,请使用“I”,如下所示

# sed -e '/two/Id' /tmp/file
one
three
Three
One

有更多方法可以做到这一点,例如我们知道要删除的文本中只有一个字母可能有不同的大小写,所以在这里

# sed -e '/[tT]wo/d' /tmp/file
one
three
Three
One

如果这里有多个字母可以是不同的大小写,那么可以使用下面的方法相应地完成相同的操作

# sed -e '/[tT][wW]o/d' /tmp/file
one
three
Three
One

忽略所有 3 个字母的大小写

# sed -e '/[tT][wW][oO]/d' /tmp/file
one
three
Three
One

要执行文件内替换,请使用以下语法

# sed -i '/two/Id' /tmp/file

或者

# sed -i '/[tT][wW][oO]/Id' /tmp/file
sed 搜索替换时如何不区分大小写

示例文件

# cat /tmp/file
one
Two
three
Three
two
One

执行不区分大小写的搜索和替换

默认情况下,如果我进行正常搜索并替换它,它将如下所示。
这里我用“new-word”替换“two”

# sed -e 's/two/new-word/g' /tmp/file
one
Two
three
Three
new-word
One

让我们对所有单词“two”执行相同的操作,而不管它的大小写,这可以使用“I”来完成,如下所示

# sed -e 's/two/new-word/Ig' /tmp/file
one
new-word
three
Three
new-word
One

如我们所见,所有出现的单词“two”都被替换为“new-word”

有更多方法可以做到这一点,例如,我们知道要替换的文本中只有一个字母可能有不同的大小写,所以可以这样写:

# sed -e 's/[tT]wo/new-word/g' /tmp/file
one
new-word
three
Three
new-word
One

如果这里有多个字母可以是不同的大小写,那么可以使用下面的方法相应地完成相同的操作

# sed -e 's/[tT][wW]o/new-word/g' /tmp/file
one
new-word
three
Three
new-word
One

忽略所有 3 个字母的大小写

# sed -e 's/[tT][wW][oO]/new-word/g' /tmp/file
one
new-word
three
Three
new-word
One

要执行文件内替换,请使用以下语法

# sed -i 's/two/new-word/Ig' /tmp/file
OR
# sed -i 's/[tT][wW]o/new-word/g' /tmp/file
日期:2020-06-02 22:17:33 来源:oir作者:oir