如何用sed匹配含不区分大小写the的行并去除空行?
解决sed匹配不区分大小写的
the并去除空行问题 原始文本
From fairest creatures we desire the increase, That The reby the rose might never die, Placeholders don't exist But as tHe riper should by time decease,
需求
匹配所有包含不区分大小写变体the的行,需覆盖The reby、tHe riper这类拆分写法的行。
之前的尝试与问题
执行命令
sed -n "/\bthe\b/ip",输出全是p:p p p原因是sed命令选项顺序错误,
p是打印命令,i是忽略大小写修饰符,位置颠倒导致解析异常。改用命令
sed -n "/\bthe\b/pi",输出接近需求但包含空行:From fairest creatures we desire the increase, That The reby the rose might never die, But as tHe riper should by time decease,问题出在
\b单词边界的匹配逻辑:The reby中的The后接空格,\b会将其识别为完整单词,但实际我们需要匹配任意位置的the(无论前后是否有空格),单词边界的限制导致匹配异常,产生空行。
解决方案
使用不区分大小写的匹配,同时去掉不必要的单词边界限制,正确排序sed命令选项:
正确命令
sed -n "/the/Ip"
命令解释
-n:仅打印匹配成功的行/the/I:I是POSIX标准的不区分大小写修饰符(部分sed版本支持小写i,但I兼容性更强),匹配任意大小写形式的thep:执行打印操作
执行结果
From fairest creatures we desire the increase, That The reby the rose might never die, But as tHe riper should by time decease,
如果你的sed版本不支持I,可以改用小写i,注意保持正确顺序:
sed -n "/the/ip"
内容的提问来源于stack exchange,提问作者aldo
相关产品推荐
相关产品推荐

