我想对通常有很长行的 HTML 文件运行 ack 或 grep 。我不想看到很长的行重复换行。但我确实希望只看到围绕与正则表达式匹配的字符串的长行的那一部分。如何使用 Unix 工具的任意组合来获得它?
10 回答
您可以使用 grep 选项-o
,可能结合将模式更改".{0,10}<original pattern>.{0,10}"
为以查看它周围的一些上下文:
-o,--仅匹配 仅显示匹配 PATTERN 的匹配行部分。
..或-c
:
-c,--计数 抑制正常输出;而是打印匹配行数 对于每个输入文件。使用 -v, --invert-match 选项(请参阅 下面),计算不匹配的行。
通过管道传输您的结果cut
。我也在考虑添加一个--cut
开关,这样你就可以说--cut=80
只能得到 80 列。
您可以使用 less 作为 ack 的寻呼机并切开长行:ack --pager="less -S"
这会保留长行但将其保留在一行而不是换行。要查看更多内容,请使用箭头键向左/向右滚动。
我为 ack 设置了以下别名来执行此操作:
alias ick='ack -i --pager="less -R -S"'
cut -c 1-100
获取从 1 到 100 的字符。
建议的方法".{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))}"
假设脚本保存为grepl
,grepl pattern file_with_long_lines
则应显示匹配行,但匹配字符串周围只有 10 个字符。
我将以下内容放入我的.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
: 不要打破长线
这就是我所做的:
function grep () {
tput rmam;
command grep "$@";
tput smam;
}
在我的 .bash_profile 中,我重写了 grep 以便它在tput rmam
之前和tput smam
之后自动运行,这禁用了包装,然后重新启用它。
Silver Searcher (ag)--width NUM
通过该选项本机支持它。它将用 替换其余较长的行[...]
。
示例(在 120 个字符后截断):
$ ag --width 120 '@patternfly'
...
1:{"version":3,"file":"react-icons.js","sources":["../../node_modules/@patternfly/ [...]
在 ack3 中,计划了一个类似的功能,但目前尚未实现。
ag
如果您愿意,也可以采用正则表达式技巧:
ag --column -o ".{0,20}error.{0,20}"