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
- 您使用
-Pzo
只打印出符合您指定模式的行。 - 包括一些
.*\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/