Case-insensitive search and replace with sed

前端 未结 8 1906
暗喜
暗喜 2020-11-28 08:51

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
<
8条回答
  •  抹茶落季
    2020-11-28 09:40

    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.

    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 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

    (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).)

提交回复
热议问题