2010-01-09 32 views
57

我想在通常有很長行的HTML文件上運行ack或grep。我不想看到重複包裹的很長的線條。但我確實希望看到圍繞與正則表達式匹配的字符串的長整行的那一部分。我如何使用Unix工具的任何組合來獲得這個結果?如何截斷由grep或ack返回的長匹配行

+1

什麼'ack'?當你不喜歡某些東西時,是否使用這個命令?像'ack file_with_long_lines | grep模式'? :-) –

+6

@Alok'ack'(在Debian上稱爲'ack-grep')在類固醇上是'grep'。它也有'--thpppt'選項(不是開玩笑)。 http://betterthangrep.com/ – ZoogieZork

+0

謝謝。我今天學到了東西。 –

回答

57

你可以使用grep選項-o,可能結合才能改變你的模式".{0,10}<original pattern>.{0,10}"看到周圍的一些背景:

 
     -o, --only-matching 
       Show only the part of a matching line that matches PATTERN. 

..或-c

 
     -c, --count 
       Suppress normal output; instead print a count of matching lines 
       for each input file. With the -v, --invert-match option (see 
       below), count non-matching lines. 
+21

例如:grep -oE「。{0,20} mysearchstring。{0,20}」myfile – Renaud

+9

您應該更改答案以添加-E選項,如@Renaud(擴展模式選項)所示,或者爲擴展上下文不會工作。 – kriss

28

管你的結果通過cut。我還在考慮添加一個--cut開關,以便您可以說--cut = 80並且只能獲得80列。

+5

如果匹配的部分不在前80個字符中怎麼辦? – Ether

+3

FWIW我附上'| cut = c1-120'到grep,爲我工作(雖然不知道如何裁剪文字) –

+17

''| cut = c1-120''不適合我,我需要做''| cut -c1-120'' –

17

你可以少用一個傳呼機作爲ack和排長線:ack --pager="less -S"這保留了長線,但將其留在一條線上而不是纏繞。要查看更多線條,請使用箭頭鍵向左/向右滾動。

我有以下別名設置爲ACK做到這一點:

alias ick='ack -i --pager="less -R -S"' 
+0

請注意,如果你總是想使用它,你可以把'--pager'命令放在〜/ .ackrc文件中。 –

+0

這聽起來像是迄今爲止最讓我感到困擾的問題。我希望我知道如何使用'ack'。 –

1

來自:http://www.topbug.net/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))}" 

假設腳本保存爲grepl,然後grepl pattern file_with_long_lines應該顯示匹配的行,但只有10個左右的匹配字符串中的字符。

0
cut -c 1-100 

會從1個字符到100