首页 文章

比赛前后的Grep角色?

提问于
浏览
103

使用这个:

grep -A1 -B1 "test_pattern" file

将在文件中匹配的模式之前和之后生成一行 . 有没有办法显示不是行而是指定数量的字符?

我文件中的行非常大,所以我对打印整行不感兴趣,而只是在上下文中观察匹配 . 有关如何做到这一点的任何建议?

5 回答

  • 83

    前3个字符后4个字符

    $> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
    23_string_and
    
  • 27
    grep -E -o ".{0,5}test_pattern.{0,5}" test.txt
    

    这将在您的模式之前和之后匹配最多5个字符 . -o开关告诉grep只显示匹配,-E使用扩展正则表达式 . 确保在表达式周围加上引号,否则shell可能会解释它 .

  • 127

    你可以用

    awk '/test_pattern/ {
        match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
    }' file
    
  • 0

    你的意思是,像这样:

    grep -o '.\{0,20\}test_pattern.\{0,20\}' file
    

    这将在 test_pattern 的任何一侧打印最多20个字符 . \{0,20\} 符号类似于 * ,但指定零到二十个重复而不是零或更多 . -o 表示仅显示匹配本身,而不是整行 .

  • 17

    使用 gawk ,您可以使用匹配功能:

    x="hey there how are you"
        echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
        ere   are
    

    如果您对 perl 没问题,可以使用更灵活的解决方案:下面将在模式之前打印三个字符,然后是实际模式,然后在模式之后打印5个字符 .

    echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
    ey there how
    

    这也可以应用于单词而不仅仅是字符 . 以下将在实际匹配字符串之前打印一个单词 .

    echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
    hey
    

    以下将在模式后打印一个单词:

    echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
    how
    

    以下将在模式之前打印一个单词,然后在模式之后打印一个单词,然后打印一个单词:

    echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
    hey there how
    

相关问题