0

I need to search for a specific string in a file and remove the all the lines in the file until i reach a specific string again. Basically i need to remove all the lines between two specific string.
e.g

 <start /myhome >
 some entries
 some entries
 <end>
 <start ~ "/myhome[^/]+" >
 some entries
 some entries
 <end>
 <start /newhome >
 some entries
 some entries
 another entry
 different string
 <end>
 <start ~ "/myhome[^/]+" >
 some entries
 some entries
 <end>

Expected output should be:

<start /myhome >
 some entries
 some entries
 <end>
 <start /newhome >
 some entries
 some entries
 another entry
 different string
 <end> 
user2589079
  • 223
  • 1
  • 3
  • 8

1 Answers1

3
perl -ne 'print if !(/<start.*?myhome\[.*?>/ .. /<end>/);' < file.txt

EDIT: Well, if you only want to use the builtins...

#!/bin/sh                                                                       

hide_from_to() {
  start=$1
  end=$2
  unset hide

  while read line
  do
    if test "$line" = "$start"
    then
      hide=1
    fi
    if test -z "$hide"
    then
      echo $line
    fi
    if test "$line" = "$end"
    then
      unset hide
    fi
  done
}

hide_from_to '<start ~ "/myhome[^/]+" >' '<end>' < a.txt
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Thanks @Amadan. how to do the same with shell scripting ? – user2589079 Nov 21 '13 at 02:33
  • 1
    That *is* shell scripting. All shell scripting is invoking various executable files to do various little tasks that combine with each other. There is no difference between `/bin/cat` and `/usr/bin/perl`, except that the latter is a bit more flexible. – Amadan Nov 21 '13 at 03:12
  • But this needs perl installed on the box. Correct me if i am wrong. I am sure most of the unix box have the perl installed but i dont want to be in the exceptional case. Thanks for the reply. – user2589079 Nov 21 '13 at 03:25
  • 1
    @user2589079 Nearly *all* UNIXY boxes have Perl. – squiguy Nov 21 '13 at 05:43
  • @Amandan I have tested the one liner and it works perfect thanks. I have a question, both the above solutions will pint the output is in it. Is there a way to just update the existing file or redirect to the new file. Then i can rename it with the original. Let me know your suggestion. – user2589079 Nov 21 '13 at 19:29
  • Redirect to new file, in both solutions: `... < a.txt > b.txt`. Edit in-place, only the first solution: `perl -i -ne ...` (not really in-place: copies original to backup, reads backup and overwrites original, deletes backup) – Amadan Nov 21 '13 at 22:36