用这个:
grep -A1 -B1 "test_pattern" file
将在文件中匹配的模式前后产生一行。是否有一种方法不显示行,而是显示指定数量的字符?
我的文件中的行相当大,所以我对打印整行不感兴趣,而只是在上下文中观察匹配。有什么建议吗?
用这个:
grep -A1 -B1 "test_pattern" file
将在文件中匹配的模式前后产生一行。是否有一种方法不显示行,而是显示指定数量的字符?
我的文件中的行相当大,所以我对打印整行不感兴趣,而只是在上下文中观察匹配。有什么建议吗?
当前回答
前3个字符,后4个字符
$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and
其他回答
你可以用
awk '/test_pattern/ {
match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file
我永远不会轻易记住这些神秘的命令修饰符,所以我把上面的答案变成了~/中的一个函数。bashrc文件:(
cgrep() {
# For files that are arrays 10's of thousands of characters print.
# Use cpgrep to print 30 characters before and after search pattern.
if [ $# -eq 2 ] ; then
# Format was 'cgrep "search string" /path/to/filename'
grep -o -P ".{0,30}$1.{0,30}" "$2"
else
# Format was 'cat /path/to/filename | cgrep "search string"
grep -o -P ".{0,30}$1.{0,30}"
fi
} # cgrep()
下面是它实际运行的样子:
$ ll /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
-rw-r--r-- 1 rick rick 25780 Jul 3 19:05 /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
$ cat /tmp/rick/scp.Mf7UdS/Mf7UdS.Source | cgrep "Link to iconic"
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
$ cgrep "Link to iconic" /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
这个文件是一个连续的25K行,使用常规的grep是不可能找到你要找的东西的。
请注意调用与grep方法并行的cgrep的两种不同方式。
有一种“更好”的方法来创建函数,其中“$2”只在设置时传递,这将节省4行代码。不过我手边没有。比如${parm2} $parm2。如果我找到了,我会修改函数和这个答案。
前3个字符,后4个字符
$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and
使用ugrep,你可以用选项-o(——only-matching)指定-ABC context,在匹配之前和/或之后显示额外的上下文字符的匹配,将匹配加上指定的-ABC宽度内的上下文。例如:
ugrep -o -C30 pattern testfile.txt
给:
1: ... long line with an example pattern to match. The line could...
2: ...nother example line with a pattern.
在终端上,同样的颜色高亮显示: 一行中的多个匹配项显示为[+nnn more]: 或者使用选项-k(——column-number)分别显示每个对象的上下文和列号: 上下文宽度是显示的Unicode字符的数量(UTF-8/16/32),而不仅仅是ASCII。
如果使用ripgreg,你会这样做:
grep -E -o ".{0,5}test_pattern.{0,5}" test.txt