grep 能否给出搜到行的行号+内容?

grep 能否给出搜到行的行号+内容?

有什么简单方法得到行号+内容??
或者偶想得到匹配行前后N行的内容,有简单方法吗??

 

grep 能否给出搜到行的行号+内容?

bash-2.05# more txt
hello.  
sed. can you tell me.
look. can you tell me.
All. hehe.
awk
who
bash-2.05# grep -n w txt
5:awk
6:who

nkoldbug 发表于 2004-03-22 15:51

grep 能否给出搜到行的行号+内容?

set a = sed -n '/...../=;q' filename;sed -n "$((a-N)),$((a+N))"p filename

c1l2d3 发表于 2004-03-22 16:42

grep 能否给出搜到行的行号+内容?

linux下可以:
grep -n -B1 -A1 "关键字" file  #匹配关键字的前一行与后一行.

bjgirl 发表于 2004-03-22 16:47

grep 能否给出搜到行的行号+内容?

[quote][i]原帖由 "c1l2d3" 发表:[/i]
linux下可以:
grep -n -B1 -A1 "关键字" file  #匹配关键字的前一行与后一行.[/quote]
you are right :oops:

r2007 发表于 2004-03-22 18:37

grep 能否给出搜到行的行号+内容?

[quote][i]原帖由 "nkoldbug"]set a = sed -n '/...../=;q' filename;sed -n "$((a-N)),$((a+N))"p filename[/quote 发表:[/i]

不知nkoldbug用的那种shell?
bash应该这样写
[code]N=1;a=`sed -n '/pattern/{=;q}' file`;sed -n "$((a-N)),$((a+N))"p file[/code]
其中=;q一定要这样写{=;q}。
不知我的理解是否正确?欢迎斧正^_^

nkoldbug 发表于 2004-03-22 21:42

grep 能否给出搜到行的行号+内容?

hehe
谢谢r2007的指正

c1l2d3 发表于 2004-03-23 08:02

grep 能否给出搜到行的行号+内容?

[quote][i]原帖由 "bjgirl"]you are right :oops:[/quote 发表:[/i]


:mrgreen: 不止一次见过mm这么写地: :oops:

li2002 发表于 2004-03-23 11:59

grep 能否给出搜到行的行号+内容?

tks

footfly 发表于 2004-03-23 13:45

grep 能否给出搜到行的行号+内容?

grep -n w txt

这里W不用引起来吗?

grep -n -B1 -A1  哈哈...又学一招
B1:before 1 line;
A1:after 1 line;
这样记起来单间有效,吾来偷师学艺,各位大人不小气吧

li2002 发表于 2004-03-23 13:56

grep 能否给出搜到行的行号+内容?

-B1 -A1 只有linux下才有吗??sco unix下好像没有这个选项

mymm 发表于 2004-03-23 14:01

grep 能否给出搜到行的行号+内容?

[quote][i]原帖由 "li2002"]-B1 -A1 只有linux下才有吗??sco unix下好像没有这个选项[/quote 发表:[/i]

可不是咋的!
grep这么优秀的参数偶的系统(AIX433)也没有!
真是嫉妒!

bjgirl 发表于 2004-03-23 14:08

grep 能否给出搜到行的行号+内容?

[quote][i]原帖由 "mymm" 发表:[/i]

可不是咋的!
grep这么优秀的参数偶的系统(AIX433)也没有!
真是嫉妒![/quote]
my GNU/linux is A best OS...
GNU,longlive ! :oops:

朽木可雕 发表于 2004-03-23 14:16

grep 能否给出搜到行的行号+内容?

[quote][i]原帖由 "r2007" 发表:[/i]
其中=;q一定要这样写{=;q}。
不知我的理解是否正确?欢迎斧正^_^[/quote]
我的是bash-2.05,这样写
N=1;a=`sed -n '/book/=' filename`;sed -n "$((a-N)),$((a+N))"p filename
就可以了。不知道加q是为什么呢?而且我按时您的做了不行

bjgirl 发表于 2004-03-23 14:27

grep 能否给出搜到行的行号+内容?

[code]n=$(sed -n '/\<keyword\>/=' file);sed -n "$((n-1)),$((n+1))p" file[/code]
测试通过

mymm 发表于 2004-03-23 14:47

grep 能否给出搜到行的行号+内容?

[code]
N=1;a=`sed -n '/pattern/{=;q}' file`;sed -n "$((a-N)),$((a+N))"p file

N=1;a=`sed -n '/pattern/=' file`;sed -n "$((a-N)),$((a+N))"p file

n=$(sed -n '/\<pattern\>/=' file);sed -n "$((n-1)),$((n+1))p" file

[/code]

均没问题!

r2007 发表于 2004-03-23 18:00

grep 能否给出搜到行的行号+内容?

不加q也可以,不过sed会一直将文件读到底,浪费时间的。

朽木可雕 发表于 2004-03-23 20:14

grep 能否给出搜到行的行号+内容?

我的系统运行
N=1;a=`sed -n '/pattern/{=;q}' file`;sed -n "$((a-N)),$((a+N))"p file
为什么会出现下面错误提示呢?
sed: 命令错乱:/pattern/{=;q}
sed: 无效选项 -- 1

john_student 发表于 2004-03-23 20:21

grep 能否给出搜到行的行号+内容?

q;即可。

mlboy2001 发表于 2011-07-13 10:15

怎么不要行号呢

 

rdcwayx 发表于 2011-07-13 10:26

[code]awk '/Your.string/{print NR ":" $0}' infile[/code]

posted @ 2011-11-24 12:09  一根骨头棒子*熬的汤  阅读(4418)  评论(0编辑  收藏  举报