不区分大小写的搜索并替换为sed [英] Case-insensitive search and replace with sed
问题描述
我正在尝试使用SED从日志文件中提取文本.我可以轻松进行搜索和替换:
I'm trying to use SED to extract text from a log file. I can do a search-and-replace without too much trouble:
sed 's/foo/bar/' mylog.txt
但是,我想使搜索不区分大小写.从我搜索过的内容来看,将i
附加到命令末尾似乎可以正常工作:
However, I want to make the search case-insensitive. From what I've googled, it looks like appending i
to the end of the command should work:
sed 's/foo/bar/i' mylog.txt
但是,这给了我一条错误消息:
However, this gives me an error message:
sed: 1: "s/foo/bar/i": bad flag in substitute command: 'i'
这里出了什么问题,我该如何解决?
What's going wrong here, and how do I fix it?
推荐答案
要明确:在 macOS 上-自Mojave(10.14)起- sed
-即 BSD 实现-不支持不区分大小写的匹配-难以置信,但确实如此. 以前接受的答案(其本身显示了 GNU sed
命令)之所以获得该状态,是因为评论中提到的基于perl
的解决方案.
To be clear: On macOS - as of Mojave (10.14) - sed
- which is the BSD implementation - does NOT support case-insensitive matching - hard to believe, but true. The formerly accepted answer, which itself shows a GNU sed
command, gained that status because of the perl
-based solution mentioned in the comments.
要使 Perl解决方案也可以通过UTF-8与外国字符一起使用,请使用类似以下内容的东西:
To make that Perl solution work with foreign characters as well, via UTF-8, use something like:
perl -C -Mutf8 -pe 's/öœ/oo/i' <<< "FÖŒ" # -> "Foo"
-
-C
假设当前语言环境是基于UTF-8的,打开了对流和文件的UTF-8支持. -
-Mutf8
告诉Perl将源代码解释为UTF-8(在这种情况下,是传递给-pe
的字符串)-这是更冗长的-e 'use utf8;'.
的等价形式. 谢谢,马克·里德 -C
turns on UTF-8 support for streams and files, assuming the current locale is UTF-8-based.-Mutf8
tells Perl to interpret the source code as UTF-8 (in this case, the string passed to-pe
) - this is the shorter equivalent of the more verbose-e 'use utf8;'.
Thanks, Mark Reed
(请注意,使用awk
也不可行,就像在macOS上的awk
(即 BWK awk ,也称为 BSD awk )似乎完全不了解语言环境-它的tolower()
和toupper()
函数会忽略外来字符(并且sub()
/gsub()
开头没有区分大小写的标志).
(Note that using awk
is not an option either, as awk
on macOS (i.e., BWK awk, a.k.a. BSD awk) appears to be completely unaware of locales altogether - its tolower()
and toupper()
functions ignore foreign characters (and sub()
/ gsub()
don't have case-insensitivity flags to begin with).)
这篇关于不区分大小写的搜索并替换为sed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!