LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1216|回复: 3

如何取出第一符合条件行和最后一个符合条件行之间的数据

[复制链接]
发表于 2011-9-16 11:11:08 | 显示全部楼层 |阅读模式
文本中间会有多个符合条件的行
发表于 2011-9-16 20:14:41 | 显示全部楼层
buffer=""
match=""
while read line
do
if 符合条件
then
echo $buffer$line
buffer=""
match=1
elif [[ $match == 1 ]]
then
buffer="$buffer$line\n"
fi
done <文件
回复 支持 反对

使用道具 举报

发表于 2011-9-17 15:26:48 | 显示全部楼层
保存为脚本, 如:script.pl

script.pl path_to_ur_file
  1. #!/usr/bin/perl
  2. $argc = @ARGV;
  3. if($argc != 2){
  4.     exit 1;
  5. }
  6. open $fh, "<", $ARGV[0];
  7. $match = $ARGV[1];
  8. $start = undef;
  9. $end = undef;
  10. $tmp = tell $fh;
  11. while(<$fh>){
  12.    if(m/$match/g){
  13.        if($start == undef){
  14.            $start = tell $fh;
  15.        } else {
  16.            $end = $tmp;
  17.        }
  18.    }
  19.    $tmp = tell $fh;
  20. }
  21. if($start && $end){
  22.     seek $fh, $start, 0;
  23.     while(<$fh>){
  24.         print $_;
  25.         $tmp = tell $fh;
  26.         if($tmp == $end){
  27.             last;
  28.         }
  29.     }
  30. } else {
  31.     print "Not Found"
  32. }
复制代码
回复 支持 反对

使用道具 举报

发表于 2011-9-17 19:51:47 | 显示全部楼层
通过grep -n exp file 可以获取所有符合条件的行号
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表