我有一个按以下方式构造的文件:
# comment with keyword One
some code here
and some more code
# another comment with keyword Two
some code
# more comments and keyword Three
lots
of
code
我试图以不区分大小写的方式提取给定关键字的注释和相应的代码行。例如:
$ cat file.txt | find_by_keyword one three
# comment with keyword One
some code here
and some more code
# more comments and keyword Three
lots
of
code
我以前使用过awk '/^#.*('$se').*$/,/^$/'
,$se
我从提供的关键字 ( (one|two)
)构建的正则表达式在哪里。但是,我无法让它不区分大小写。用不同的案例来置换用户输入似乎不是一个好主意......
有任何想法吗?
如果您有 GNU sed,则可以使用不区分大小写的模式匹配:
#!/usr/bin/env bash
pattern=$(IFS='|'; printf '%s' "$*")
sed -En "/^#.*($pattern)/I,/^$/p"
第一个命令构建一个模式,如one|three
; sed 命令使用扩展的正则表达式 ( -E
) 并默认禁止输出 ( -n
);然后打印从匹配模式的任何注释行(I
不区分大小写匹配的标志)到下一个空行的范围。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句