Chinaunix

标题: 求教一个初级问题:sed查找增加内容的初级问题 [打印本页]

作者: richardxie    时间: 2009-04-25 23:02
标题: 求教一个初级问题:sed查找增加内容的初级问题
求教一个初级问题,在一个文件里面,如何在匹配单词的第一次匹配或者最后一次匹配后面追加文本?

如匹配shell单词,
apple
shell -->这后面增加内容
shell
apple
shell --->另外一个场景,在这后面增加内容
作者: kwokcn    时间: 2009-04-26 00:27
用awk可以吗?
我也一直对怎么用sed判断“第一次”和“最后一次”很困惑……


  1. [root@bj_manager add]# cat 1
  2. apple
  3. shell
  4. shell
  5. apple
  6. shell
  7. apple
  8. [root@bj_manager add]# awk '$0~"shell"&&!k{print $0"\n1111111111";k=1;next}{print}' 1
  9. apple
  10. shell
  11. 1111111111
  12. shell
  13. apple
  14. shell
  15. apple
  16. [root@bj_manager add]# sed ''$(awk '$0~"shell"{k=NR}END{print k}' 1)' a \1111111' 1
  17. apple
  18. shell
  19. shell
  20. apple
  21. shell
  22. 1111111
  23. apple
复制代码

作者: ywlscpl    时间: 2009-04-26 00:49
awk的:
第一次匹配后加 awk -v RS="###" '{sub(/shell/,"&加的内容")}1' file
最后一次匹配后加 awk -v RS="###" '{print gensub(/shell/,"&加的内容",gsub(/shell/,"&"))}' file
作者: kwokcn    时间: 2009-04-26 01:11
原帖由 ywlscpl 于 2009-4-26 00:49 发表
awk的:
第一次匹配后加 awk -v RS="###" '{sub(/shell/,"&加的内容")}1' file
最后一次匹配后加 awk -v RS="###" '{print gensub(/shell/,"&加的内容",gsub(/shell/,"&"))}' file

处理超过3G的大文件的时候内存会有问题。
不过效率确实要好~:)
学习了~
作者: ywlscpl    时间: 2009-04-26 07:33
标题: 回复 #4 kwokcn 的帖子
可能是把所有内容当一行处理的原因
作者: ly5066113    时间: 2009-04-26 09:23
标题: 回复 #1 richardxie 的帖子
try:

  1. $ cat urfile
  2. apple
  3. shell
  4. shell
  5. apple
  6. shell
  7. $ cat test.sed
  8. #! /bin/sed -f
  9. /shell/{
  10.         x
  11.         /^$/{
  12.                 x
  13.                 s/$/ hello/
  14.                 h
  15.                 b
  16.         }
  17.         x
  18.         :a
  19.         N
  20.         /shell$/{
  21.                 h
  22.                 s/\n[^\n]*$//p
  23.                 g
  24.                 s/.*\n//
  25.         }
  26.         $!ba
  27.         s/^\([^\n]*\)/\1 hello/
  28. }
  29. $ sed -f test.sed urfile
  30. apple
  31. shell hello
  32. shell
  33. apple
  34. shell hello
复制代码

作者: 我是DBA    时间: 2009-04-27 09:06
标题: 回复 #6 ly5066113 的帖子
这个太强大了。得好好研究一下。




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