需要使用shell脚本删除txt文件中的特定行

时间:2013-11-21 00:36:59

标签: regex perl bash shell perlscript

我需要在文件中搜索特定字符串并删除文件中的所有行,直到我再次到达特定字符串。基本上我需要删除两个特定字符串之间的所有行。
例如

 <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>

预期输出应为:

<start /myhome >
 some entries
 some entries
 <end>
 <start /newhome >
 some entries
 some entries
 another entry
 different string
 <end> 

1 个答案:

答案 0 :(得分:3)

perl -ne 'print if !(/<start.*?myhome\[.*?>/ .. /<end>/);' < file.txt
编辑:好吧,如果你只想使用内置...

#!/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