Chinaunix

标题: 获取含有指定字符串的行和它的上一行 [打印本页]

作者: 流星奇幻    时间: 2012-01-06 09:56
标题: 获取含有指定字符串的行和它的上一行
本帖最后由 流星奇幻 于 2012-01-06 09:57 编辑

cat  a.tx

12345
错误1
abcdef
aaaaaa
错误

“错误”是固定的字符串,我要想获取的结果是含有错误的行和它的上一行,如下:
12345
错误1
aaaaaa
错误

作者: yangkyo821    时间: 2012-01-06 10:01
  1. grep '错误' -B1
复制代码

作者: jason680    时间: 2012-01-06 10:06
回复 1# 流星奇幻

by awk

awk '/错误/{print a"\n"$0}{a=$0}' FILE
作者: ri0day    时间: 2012-01-06 10:16
本帖最后由 ri0day 于 2012-01-06 10:16 编辑

[root@hostkiller ~]# cat 2.txt
12345
错误1
abcdef

后:
[root@hostkiller ~]# grep '错误1' -A 1 2.txt
abcdef
前:
[root@hostkiller ~]# grep '错误1' -B 1 2.txt
12345
作者: Shell_HAT    时间: 2012-01-06 14:07
  1. sed '$!N;/错误/P;D' urfile
复制代码

作者: huatuo20002008    时间: 2012-01-06 19:39
回复 3# jason680
巧!妙!如果需要打印本行和下一行,用awk如何实现?
  
作者: godymoon    时间: 2012-01-06 19:41
  1. my_host:~ # cat 1.txt
  2. Bfore
  3. CU
  4. After
  5. my_host:~ # grep -B1 CU 1.txt
  6. Bfore
  7. CU
  8. my_host:~ # grep -A1 CU 1.txt
  9. CU
  10. After
  11. my_host:~ #
复制代码

作者: dn833    时间: 2012-01-06 23:24
huatuo20002008 发表于 2012-01-06 19:39
回复 3# jason680
巧!妙!如果需要打印本行和下一行,用awk如何实现?


awk '/关键字/{getline v;print $0"\n"v}'
作者: suifeng2012    时间: 2012-01-07 21:19
Great! 请解释一下




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2