105

我想对通常有很长行的 HTML 文件运行 ack 或 grep 。我不想看到很长的行重复换行。但我确实希望只看到围绕与正则表达式匹配的字符串的长行的那一部分。如何使用 Unix 工具的任意组合来获得它?

4

10 回答 10

107

您可以使用 grep 选项-o,可能结合将模式更改".{0,10}<original pattern>.{0,10}"为以查看它周围的一些上下文:

       -o,--仅匹配
              仅显示匹配 PATTERN 的匹配行部分。

..或-c

       -c,--计数
              抑制正常输出;而是打印匹配行数
              对于每个输入文件。使用 -v, --invert-match 选项(请参阅
              下面),计算不匹配的行。
于 2010-01-09T20:21:56.840 回答
54

通过管道传输您的结果cut。我也在考虑添加一个--cut开关,这样你就可以说--cut=80只能得到 80 列。

于 2010-01-09T21:19:54.127 回答
26

您可以使用 less 作为 ack 的寻呼机并切开长行:ack --pager="less -S" 这会保留长行但将其保留在一行而不是换行。要查看更多内容,请使用箭头键向左/向右滚动。

我为 ack 设置了以下别名来执行此操作:

alias ick='ack -i --pager="less -R -S"' 
于 2012-06-14T18:02:17.623 回答
11

grep -oE ".\{0,10\}error.\{0,10\}" mylogfile.txt

在您无法使用的特殊情况下,请-E改用小写字母-e

解释: 在此处输入图像描述

于 2020-07-30T02:06:40.733 回答
9
cut -c 1-100

获取从 1 到 100 的字符。

于 2018-02-23T18:24:44.353 回答
2

取自:http ://www.topbug.ne​​t/blog/2016/08/18/truncate-long-matching-lines-of-grep-a-solution-that-preserves-color/

建议的方法".{0,10}<original pattern>.{0,10}"非常好,只是突出显示的颜色经常被弄乱了。我创建了一个具有类似输出的脚本,但颜色也被保留:

#!/bin/bash

# Usage:
#   grepl PATTERN [FILE]

# how many characters around the searching keyword should be shown?
context_length=10

# What is the length of the control character for the color before and after the
# matching string?
# This is mostly determined by the environmental variable GREP_COLORS.
control_length_before=$(($(echo a | grep --color=always a | cut -d a -f '1' | wc -c)-1))
control_length_after=$(($(echo a | grep --color=always a | cut -d a -f '2' | wc -c)-1))

grep -E --color=always "$1" $2 |
grep --color=none -oE \
    ".{0,$(($control_length_before + $context_length))}$1.{0,$(($control_length_after + $context_length))}"

假设脚本保存为greplgrepl pattern file_with_long_lines则应显示匹配行,但匹配字符串周围只有 10 个字符。

于 2016-08-19T01:51:37.390 回答
1

我将以下内容放入我的.bashrc

grepl() {
    $(which grep) --color=always $@ | less -RS
}

然后,您可以grepl在命令行上使用任何可用于grep. 使用箭头键查看较长行的尾部。用于q退出。

解释:

  • grepl() {:定义将在每个(新)bash 控制台中可用的新函数。
  • $(which grep): 获取grep. (Ubuntu 为它定义了一个别名,grep它等同于grep --color=auto。我们不想要那个别名,而是原来的grep。)
  • --color=always:着色输出。(--color=auto从别名不起作用,因为grep检测到输出被放入管道并且不会对其着色。)
  • $@: 把给grepl函数的所有参数放在这里。
  • less:显示使用的行less
  • -R: 显示颜色
  • S: 不要打破长线
于 2019-11-06T10:28:08.687 回答
1

这就是我所做的:

function grep () {
  tput rmam;
  command grep "$@";
  tput smam;
}

在我的 .bash_profile 中,我重写了 grep 以便它在tput rmam之前和tput smam之后自动运行,这禁用了包装,然后重新启用它。

于 2019-11-21T18:37:44.537 回答
1

Silver Searcher (ag)--width NUM通过该选项本机支持它。它将用 替换其余较长的行[...]

示例(在 120 个字符后截断):

 $ ag --width 120 '@patternfly'
 ...
 1:{"version":3,"file":"react-icons.js","sources":["../../node_modules/@patternfly/ [...]

在 ack3 中,计划了一个类似的功能,但目前尚未实现。

于 2021-06-24T08:43:06.610 回答
0

ag如果您愿意,也可以采用正则表达式技巧:

ag --column -o ".{0,20}error.{0,20}"
于 2021-05-12T19:10:45.680 回答