regex - 使用多行正则表达式获取 grep 上下文

标签 regex bash grep

grep 的 -Pz 和 -C 选项可以一起使用吗?我正在尝试匹配相邻行的短语并打印它的上下文。扩展的正则表达式和上下文选项单独工作,但不能像这样一起工作(打印整个文件):

grep -C 2 -Pz ".*word.*\n.*phrase.*" file.txt

文件.txt的内容:

line 1
line 2
line 3
line 4
line 5
word ...other text
phrase ...yet another text
line 6
line 7
line 8
line 9
line 10

预期结果:

line 4
line 5
word ...other text
phrase ...yet another text
line 6
line 7

最佳答案

没有。你不能。不允许。 -Pz-C 不喜欢对方。不要害怕,有一种方法可以做你想做的事:

grep -Pzo ".*\n.*\n.*.*word.*\n.*phrase.*\n.*\n.*" file.txt

或者你可以参数化它

BEFORE=2
AFTER=2
grep -Pzo "(.*\n){$BEFORE}.*word.*\n.*phrase.*(\n.*){$AFTER}" file.txt
  1. 您使用 -Pzo 只打印出符合您指定模式的行。
  2. 包括一些 .*\n.* 来填充您的模式字符串。

您可能会发现这个 bash 函数很有用:

function pad_grep()(
        usage() { echo "Usage: $0 [-ABC] [EXPR] [FILE]" 1>&2; exit 1; }

        A=0
        B=0
        while getopts "A:B:C:" flag; do
                case "$flag" in
                        A) A=$OPTARG;;
                        B) B=$OPTARG;;
                        C) A=$OPTARG;B=$OPTARG;;
                        *) usage;;
                esac
        done
        EXPR=${@:$OPTIND:1}
        FILE=${@:$OPTIND+1:1}

        # Error checking
        [ ${#EXPR} -eq 0 ] && usage
        [[ ${#FILE} -ne 0 && ! -f ${FILE} ]] && usage

        grep -Pzo "(.*\n){$B}${EXPR}(\n.*){$A}" $FILE
)

# Do it yourself
grep -Pzo ".*\n.*\n.*\n.*.*word.*\n.*phrase.*\n.*\n.*" file.txt

# Use the function
pad_grep -B 3 -A 2 '.*word.*\n.*phrase.*' file.txt
pad_grep -C 2 '.*word.*\n.*phrase.*' file.txt

关于regex - 使用多行正则表达式获取 grep 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64757468/

相关文章:

linux - Grep nmap 输出

regex - Grep 中间的通配符

javascript - 如何使用正则表达式用新行替换段落元素?

linux - 关于使用 bash/sed/awk 脚本重新排序网络路由文件的方法的思考

perl - 使用 Perl 或 shell 在文件中查找模式

bash - 在bash脚本中添加两位小数

python - 使用 python 子进程将文件从 .sam 转换为 .bam

java - 使用文本文件中的参数的replaceAll()方法

php - 查找大括号内的文本并替换包括大括号的文本

javascript - 带通配符的姓氏正则表达式