How to match and remove the content preceding it from a file in unix

88 views Asked by At

I have a mysql dump file, and i want to remove the content of the file after "-- Final view structure for view view_oss_user" using sed/perl. The input file is something like this : Content :

rom `target` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `view_oss_user`
--

/*!50001 DROP VIEW IF EXISTS `view_oss_user`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = latin1 */;
/*!50001 SET character_set_results     = latin1 */;

And the output should be like below :

rom `target` */;
    /*!50001 SET character_set_client      = @saved_cs_client */;
    /*!50001 SET character_set_results     = @saved_cs_results */;
    /*!50001 SET collation_connection      = @saved_col_connection */;

    --
2

There are 2 answers

3
josifoski On BEST ANSWER

with GNU sed

sed -n '1,/-- Final view structure for view `view_oss_user`/p'

this will print lines from 1 till pattern found, others will not be printed

or if you want to exclude pattern line then

sed -n '1,/-- Final view structure for view `view_oss_user`/p' | sed '$d'
0
Neil H Watson On
#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my @new_dump;
my $flag = 0;

while(<DATA>)
{
   if ( m/-- Final view structure for view `view_oss_user`/ )
   {
      $flag++;
   }
   push @new_dump, $_ unless $flag > 0;
}

print Dumper( \@new_dump );

__DATA__
rom `target` */;
/*!50001 SET character_set_client      = @saved_cs_client */;
/*!50001 SET character_set_results     = @saved_cs_results */;
/*!50001 SET collation_connection      = @saved_col_connection */;

--
-- Final view structure for view `view_oss_user`
--

/*!50001 DROP VIEW IF EXISTS `view_oss_user`*/;
/*!50001 SET @saved_cs_client          = @@character_set_client */;
/*!50001 SET @saved_cs_results         = @@character_set_results */;
/*!50001 SET @saved_col_connection     = @@collation_connection */;
/*!50001 SET character_set_client      = latin1 */;
/*!50001 SET character_set_results     = latin1 */;

Run it:

 ./perl 
$VAR1 = [
          'rom `target` */;
',
          '/*!50001 SET character_set_client      = @saved_cs_client */;
',
          '/*!50001 SET character_set_results     = @saved_cs_results */;
',
          '/*!50001 SET collation_connection      = @saved_col_connection */;
',
          '
',
          '--
'
        ];